如何使用 LINQ 在 C# 中重构对象?
我有一个数据集如下:
[
{
"Id": 1,
"Country": "Uruguay",
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 2,
"Country": "Uruguay",
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 3,
"Country": "Germany",
"Name": "Foo",
"Status": "Completed",
},
]
我想按国家对其进行转换和排序,使其如下所示:
[
{
"Country": "Uruguay",
"Details": [
{
"Id": 1,
"Name": "Foo",
"Status": "Completed",
},
{
"Id": 2,
"Name": "Foo",
"Status": "Completed",
},
],
},
{
"Country": "Germany",
"Details": [
{
"Id": 3,
"Name": "Foo",
"Status": "Completed",
},
],
},
],
这些是 C# 中的类:
public class Countries {
public int Id { get; set; }
public string Country { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
public class Details {
public int Id { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
public class CountryList {
public string Country { get; set; }
public List<Details> Details { get; set; }
}
我尝试过的一些内容如下所示:
var foo = countries
.GroupBy(x => new Details { Id = x.Id, Name = x.Name, Status = x.Status })
.Select( y => new CountryList
{
// Country = y.Key.
}
var foo = countries
.GroupBy(x => x.Country)
.Select( y => new CountryList
{
// Country = y.Key.
Details = y.GroupBy(a => new Details
{
Id = a.Id,
Name = a.Name,
Status = a.Status
}).ToList()
}
我无法确定如何使用LINQ 来解决这个问题。我过去做过一些 GroupBy 操作,但我无法解决这个问题。如何将数据集转换为所需的结果?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不需要第二个 GroupBy
You do not need second GroupBy
您可以利用
.GroupBy()
重载,可让您定义resultSelector
来创建CountryList
并填充他们的详细信息
:,
(国家/地区,比赛)=> new CountryList() { ... }
是resultSelector
。小提琴示例此处。
You can take advantage of the
.GroupBy()
overload that lets you define aresultSelector
to create yourCountryList
s and populate theirDetails
:,
( country, matches ) => new CountryList() { ... }
being theresultSelector
.Example fiddle here.
试试这个
try this