在列表中仅创建一列子列表

问题描述 投票:0回答:1

我有两个具有不同地址的sql记录,我正在尝试通过使用子列表将其作为一个记录

public class spproperty
    {
        public string Name{ get; set; }
        public string Addr{ get; set; }
        public int ID{ get; set; }
    }


List<spproperty> lst = new List<spproperty>();
    lst = db.sp_getDetails(inputParameter).ToList();//gets result from stored procedure as in example

示例:

Name         Addr              ID
John         Florida           234
John         Arizona           234

列表中json中的预期输出

[
  {
    "Name": "John",
    "Addresses" : {
    "Addr" : "Florida",
    "Addr" : "Arizona"
  },
    "ID": 234,
  }
]

我在xelement中尝试了有效的数据集,列表中的任何建议

c# list asp.net-web-api2
1个回答
1
投票

您可以按名称和ID分组,然后使用linq列出所需的格式化列表。我认为以下代码将适合您的情况:

var desiredList = lst.GroupBy(x => new { Name = x.Name, ID = x.ID })
                     .Select(x => new
                     {
                         Name = x.FirstOrDefault().Name,
                         Addresses = x.Select(y => y.Addr).ToList(),
                         ID = x.FirstOrDefault().ID
                     }).ToList();

之后,您可以根据需要将结果转换为Json。

© www.soinside.com 2019 - 2024. All rights reserved.