1

在下面的代码中,检查以下行:

//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;
        }
    }
}
4

1 回答 1

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;
}
于 2013-07-27T00:18:20.663 回答