C# 在列表中仅为一列创建子列表
我有两个地址不同的sql记录,我试图通过使用子列表将其作为一个记录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>();
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();