Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在列表中仅为一列创建子列表_C#_List_Asp.net Web Api2 - Fatal编程技术网

C# 在列表中仅为一列创建子列表

C# 在列表中仅为一列创建子列表,c#,list,asp.net-web-api2,C#,List,Asp.net Web Api2,我有两个地址不同的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>();

我有两个地址不同的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
列表中预期的json输出

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

我在xelement中尝试使用数据集,它起作用了,任何关于列表的建议都可以按名称和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。

您可以尝试Linq。使用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();