如何使用LINQ创建嵌套的分组字典? [英] How do I create a nested group-by dictionary using LINQ?
本文介绍了如何使用LINQ创建嵌套的分组字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用LINQ为下表创建嵌套分组?我想按Code
分组,然后按Mktcode
分组.
How would I create a nested grouping for the table below, using LINQ? I want to group by Code
, then by 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
最后我想要一本字典,就像
I'd like a dictionary, in the end, like
Dictionary<Code, List<Dictionary<Mktcode, List<Id>>>>
所以这本字典的值应该是
So the values of this dictionary would be
{1, ({10,(0001,0012)}, {20,(0010,0014)}, {30, (0002, 0005)})},
{2, ({20,(0001, 0010)}, {30, (0020)} )}
推荐答案
我会这样想:
- 您主要是按代码分组,因此请先这样做
- 对于每个组,您仍然可以获得结果列表-因此请在此处应用另一个分组.
类似的东西:
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>>
-我认为这就是您想要的.不过,这是完全未经测试的.
That will give you a Dictionary<Code, Lookup<MktCode, Id>>
- I think that's what you want. It's completely untested though.
这篇关于如何使用LINQ创建嵌套的分组字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文