2013-07-27 20 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

謝謝!這是我需要的。 –