gpt4 book ai didi

c# - 按属性分类的正确方法

转载 作者:行者123 更新时间:2023-11-30 14:57:14 29 4
gpt4 key购买 nike

我创建了一个按属性分类(或分组)的 C# LINQ 查询,我几乎可以肯定有更好的方法。我的项目充满了这些疑问,所以我对如何以正确的方式实现这一点非常感兴趣。

我的查询是这样的:

var g = _repository.GetEmployees();
var result =
g.GroupBy(x => x.City, (key, group) => group.First())
.Select(x => new {
city = x.City,
employees = g
.Where(y=>y.EmployeeID == x.EmployeeID)
.Select(y=> new {
fullname = y.FirstName + " " + y.LastName,
title = y.Title
})
.OrderBy(y=>y.fullname)
})
.OrderBy(x => x.city);

JSON 输出示例:

[
{
"city":"Barcelona",
"employees":[
{
"fullname":"Foo Bar",
"title":"Help Desk Technician"
},
{
"fullname":"Lorem Ipsum",
"title":"Information Technology Director"
}
]
},
{
"city":"London",
"employees":[
{
"fullname":"Le Query",
"title":"Information Technology Manager"
},
{
"fullname":"Please Help",
"title":"Management Information Systems Director"
}
]
}
]

结果很好。实现它的最佳方法是什么?

最佳答案

听起来你只是想要:

var result = g.GroupBy(x => x.City, (key, group) => new {
city = key,
employees = group.Select(emp => new {
fullname = emp.FirstName + " " + emp.LastName,
title = emp.Title
})
});

换句话说,您只是为每个组提供一个投影,即“城市的匿名类型,以及该城市的所有员工”。

关于c# - 按属性分类的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21158223/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com