如何使用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<Code, List<Dictionary<Mktcode, List<Id>>>>
所以这本词典的值是
{1, ({10,(0001,0012)}, {20,(0010,0014)}, {30, (0002, 0005)})},
{2, ({20,(0001, 0010)}, {30, (0020)} )}
答案 0 :(得分: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<Code, Lookup<MktCode, Id>>
- 我想想这就是你想要的。但它完全未经测试。
答案 1 :(得分:16)
您可以使用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
}
};
答案 2 :(得分:12)
我是这样做的:
Dictionary<Code, Dictionary<MktCode, List<Id>>> 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()
)
)