如何使用LINQ为下表创建嵌套分组?我想分组Code
,然后分组Mktcode
.
Code Mktcode Id ==== ======= ==== 1 10 0001 2 20 0010 1 10 0012 1 20 0010 1 20 0014 2 20 0001 2 30 0002 1 30 0002 1 30 0005
我最喜欢的是字典
Dictionary>>>
所以这本词典的价值就是
{1, ({10,(0001,0012)}, {20,(0010,0014)}, {30, (0002, 0005)})}, {2, ({20,(0001, 0010)}, {30, (0020)} )}
Jon Skeet.. 26
我会这样想的:
您主要是按代码分组,所以首先要这样做
对于每个组,您仍然有一个结果列表 - 所以在那里应用另一个分组.
就像是:
var groupedByCode = source.GroupBy(x => x.Code); var groupedByCodeAndThenId = groupedByCode.Select(group => new { Key=group.Key, NestedGroup = group.ToLookup (result => result.MktCode, result => result.Id)); var dictionary = groupedByCodeAndThenId.ToDictionary (result => result.Key, result => result.NestedGroup);
这会给你一个Dictionary
>
- 我认为这就是你想要的.但它完全未经测试.
我会这样想的:
您主要是按代码分组,所以首先要这样做
对于每个组,您仍然有一个结果列表 - 所以在那里应用另一个分组.
就像是:
var groupedByCode = source.GroupBy(x => x.Code); var groupedByCodeAndThenId = groupedByCode.Select(group => new { Key=group.Key, NestedGroup = group.ToLookup (result => result.MktCode, result => result.Id)); var dictionary = groupedByCodeAndThenId.ToDictionary (result => result.Key, result => result.NestedGroup);
这会给你一个Dictionary
>
- 我认为这就是你想要的.但它完全未经测试.
您可以使用构建查找(种类的词典<,List <>>) group by into
var lines = new [] { new {Code = 1, MktCode = 10, Id = 1}, new {Code = 2, MktCode = 20, Id = 10}, new {Code = 1, MktCode = 10, Id = 12}, new {Code = 1, MktCode = 20, Id = 10}, new {Code = 1, MktCode = 20, Id = 14}, new {Code = 2, MktCode = 20, Id = 1}, new {Code = 2, MktCode = 30, Id = 2}, new {Code = 1, MktCode = 30, Id = 2}, new {Code = 1, MktCode = 30, Id = 5}, }; var groups = from line in lines group line by line.Code into codeGroup select new { Code = codeGroup.Key, Items = from l in codeGroup group l by l.MktCode into mktCodeGroup select new { MktCode = mktCodeGroup.Key, Ids = from mktLine in mktCodeGroup select mktLine.Id } };
这是我如何做到的:
Dictionary>> myStructure =
myList
.GroupBy(e => e.Code)
.ToDictionary(
g => g.Key,
g => g
.GroupBy(e => e.Mktcode)
.ToDictionary(
g2 => g2.Key,
g2 => g2.Select(e => e.Id).ToList()
)
)
这是过程的细分:
按代码对元素进行分组,并创建一个外部字典,其中键是该代码.
myList .GroupBy(e => e.Code) .ToDictionary( g => g.Key,
对于外部字典中的每个键,通过Mktcode重新组合元素并创建内部字典.
g => g .GroupBy(e => e.Mktcode) .ToDictionary( g2 => g2.Key,
对于内部字典中的每个键,投影这些元素的id并将其转换为列表.
g2 => g2.Select(e => e.Id).ToList() ) )