我有一个 C# 字典 Dictionary<MyKey, MyValue>
我想把它分成 Dictionary<MyKey, MyValue>
的集合, 基于 MyKey.KeyType
. KeyType
是一个枚举。
然后我会得到一个包含键值对的字典,其中 MyKey.KeyType = 1
, 和另一本词典,其中 MyKey.KeyType = 2
, 等等。
有没有好的方法,比如使用 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
如果你想要一个最终由“KeyType”键控的字典的字典,方法是类似的:
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# - 有没有办法将 C# 泛型字典拆分成多个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2177667/