MSDN在解释LINQ中的嵌套组方面做得非常糟糕: https://docs.microsoft.com/en-us/dotnet/csharp/linq/create-a-nested-group
以这个例子为例:
IEnumerable<IGrouping<Gender, IGrouping<Job, Person>>> query =
from person in peopleList
group person by person.Gender into genderGroup
from jobGroup (
from person in genderGroup
group person by person.Job
)
group jobGroup by genderGroup.Key;
我的问题:
答案 0 :(得分:0)
from person in genderGroup
group person by person.Job
此子查询迭代相同性别的人,因此按工作将男性分组,然后按工作将女性分组,依此类推。如果使用peopleList
而不是genderGroup
,则查询将仅按作业对学生进行分组,并且不会嵌套嵌套。
group jobGroup by genderGroup.Key;
这按内部组的键(性别)对内部组而不是人员进行分组。假设有四个jobGroup
:男性程序员,男性设计师,女性程序员和女性设计师。该查询按性别将这四个组分组,从而产生一个嵌套的组:
male (outer group's key)
male programmers
male designers
female (outer group's key)
female programmers
female designers
为了更好地理解,我建议您在Visual Studio和set breakpoints inside the LINQ statement中运行此小代码,以了解会发生什么。