本文介绍了有没有办法将C#通用字典分割成多个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个C#字典字典< MyKey,MyValue>
,我想将其拆分为 Dictionary< MyKey,MyValue> / code>,基于 MyKey.KeyType
。 KeyType
是一个枚举。
然后我会留下一个包含键值对的字典,其中 MyKey.KeyType = 1
,另一个字典 MyKey.KeyType = 2
等等。
有没有一个很好的方法,例如使用Linq?
解决方案 var dictionaryList =
myDic.GroupBy(pair => pair.Key.KeyType)
.OrderBy(gr => gr.Key)/ /通过KeyType
.Select(gr => gr.ToDictionary(item => item.Key,item => item.Value))对结果列表进行排序
.ToList(); //获取
中的字典列表
如果您想要一个由KeyType键入的词典字典最后,方法类似:
var dictionaryOfDictionaries =
myDic.GroupBy(pair => pair .Key.KeyType)
.ToDictionary(gr => gr.Key,//外部字典的键
gr => gr.ToDictionary(item => item.Key,// key的内部词典
item => item.Value)); // value
I have a C# dictionary Dictionary<MyKey, MyValue>
and I want to split this into a collection of Dictionary<MyKey, MyValue>
, based on MyKey.KeyType
. KeyType
is an enumeration.
Then I would be left with a dictionary containing key-value pairs where MyKey.KeyType = 1
, and another dictionary where MyKey.KeyType = 2
, and so on.
Is there a nice way of doing this, such as using Linq?
解决方案 var dictionaryList =
myDic.GroupBy(pair => pair.Key.KeyType)
.OrderBy(gr => gr.Key) // sorts the resulting list by "KeyType"
.Select(gr => gr.ToDictionary(item => item.Key, item => item.Value))
.ToList(); // Get a list of dictionaries out of that
If you want a dictionary of dictionaries keyed by "KeyType" in the end, the approach is similar:
var dictionaryOfDictionaries =
myDic.GroupBy(pair => pair.Key.KeyType)
.ToDictionary(gr => gr.Key, // key of the outer dictionary
gr => gr.ToDictionary(item => item.Key, // key of inner dictionary
item => item.Value)); // value
这篇关于有没有办法将C#通用字典分割成多个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!