2013-07-27 23 views
1

在下面的代码,请检查下面一行:如何组合对象以便与JSON同时显示所有对象?

//here I need to put the object "nd" into a "bucket" so that I can finish the loop and then return EVERYTHING together. 

我的问题是,如何合并对象返回的JSON?我需要“结合”的原因是因为为这个类的特定属性赋值的循环。一旦完成每个类的获取属性值,我需要将所有内容都返回为JSON。

namespace X 
{ 
    public class NotificationsController : ApiController 
    { 
     public List<NotificationTreeNode> getNotifications(int id) 
     { 
      var bo = new HomeBO(); 
      var list = bo.GetNotificationsForUser(id); 
      var notificationTreeNodes = (from GBLNotifications n in list 
             where n.NotificationCount != 0 
             select new NotificationTreeNode(n)).ToList(); 

      foreach (var notificationTreeNode in notificationTreeNodes) 
      { 
       Node nd = new Node(); 
       nd.notificationType = notificationTreeNode.NotificationNode.NotificationType; 

       var notificationList = bo.GetNotificationsForUser(id, notificationTreeNode.NotificationNode.NotificationTypeId).Cast<GBLNotifications>().ToList(); 
       List<string> notificationDescriptions = new List<string>(); 

       foreach (var item in notificationList) 
       { 
        notificationDescriptions.Add(item.NotificationDescription); 
       } 

       nd.notifications = notificationDescriptions; 

       //here I need to put the object "nd" into a "bucket" so that I can finish the loop and then return EVERYTHING together. 
      } 

      return bucket; 
     } 
    } 

    public class Node 
    { 
     public string notificationType 
     { 
      get; 
      set; 
     } 

     public List<string> notifications 
     { 
      get; 
      set; 
     } 
    } 
} 

回答

1

您可以在每个项目只需添加到列表,你通过源集合迭代:

public List<Node> getNotifications(int id) 
{ 
    var bucket = new List<Node>(notificationTreeNodes.Count); 

    foreach (var notificationTreeNode in notificationTreeNodes) 
    { 
     Node nd = new Node(); 
     ... 

     bucket.Add(nd); 
    } 

    return bucket; 
} 
+0

谢谢!这是我需要的。 –