问题描述
如何使用LINQ按属性分组并选择其他属性作为列表?
How to group by Properties and select other properties as lists using LINQ?
我不擅长解释,所以这里有一个例子:
I'm bad at explaining it so here's an example:
让我们说我有一个C#对象列表,可以像这样用JSON表示:
Lets say I have a list of C# objects that can be represented in JSON like this:
[
{ "id":123, "name":"John", "carId":1, "carAge":3 },
{ "id":123, "name":"John", "carId":2, "carAge":4 },
{ "id":4, "name":"Mary", "carId":3, "carAge":3 },
{ "id":4, "name":"Mary", "carId":4, "carAge":3 },
{ "id":123, "name":"John", "carId":5, "carAge":3 }
]
在所有这些对象中,只有 carId
是唯一的.
Among all those objects only carId
is unique.
我想按人员详细信息对它们进行分组,并将这些详细信息与相连的汽车详细信息合并.
I would like to group them by person details and join those details with connected car details.
最终结果如下所示,但作为c#对象:
The end result would look like this but as c# objects:
[
{"id":123, "name":"John",
[
{"carId":1, "carAge":3},
{"carId":2, "carAge":4},
{"carId":5, "carAge":3}
]
},
{"id":4, "name":"Mary",
[
{"carId":3, "carAge":3},
{"carId":4, "carAge":3}
]
}
]
我被困在
list.GroupBy(x => new { x.Id, x.Name })
因为我不需要任何聚合函数,而只需要选择即可.
because I don't need any aggregate functions but only selection.
很抱歉没有发布更多代码,这是一个简化的版本,真实内容具有更多过滤和复杂的领域特定术语.
I apologize for not posting more code, this is a simplified version, the real thing has more filtering and convoluted domain specific terminology.
一切都在内存中完成-无需担心DB.
Everything is done in memory - without DB to worry about.
推荐答案
为 group _ by _
表达式的每个部分创建一个具有所需字段的匿名对象.
for each section of the group _ by _
expression create an anonymous object with the fields you want.
通过以下任何一种方式,您将为每个键构造一个嵌套集合-使用 GroupBy
时,它不仅涉及聚合,而且还涉及对特定数据组的操作.一种情况是聚合方法.
With any of the following ways you will construct a nested collection for each of your keys - when using a GroupBy
it is not just about aggregations but about operations on specific groups of data. One case of it is aggregation methods.
var result = from item in data
group new { item.carId, item.carAge } by new {item.id, item.name} into g
select g;
另一种方法是
var result = from item in data
group by new {item.id, item.name} into g
select new {
g.Key,
Data = g.Select(i => new {i.carId, i.carAge})
};
使用您尝试使用的方法语法,可以使用以下重载:
Using method syntax as you tried you can use the following overload:
var result = data.Group(k => new {k.id, k.name},
e => new {e.carId, e.carAge});
或者如果不是,只需添加一个 Select
进行投影:
Or if not the just add a Select
for projection:
var result = data.Group(k => new {k.id, k.name})
.Select(g => new {
g.Key,
Data = g.Select(i => new {i.carId, i.carAge})
});
这篇关于Linq GroupBy并选择其他属性作为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!