有没有办法将C#通用字典拆分成多个字典?

Fio*_*ite 4 c# linq dictionary split

我有一个C#字典Dictionary<MyKey, MyValue>,我想把它拆分成一个Dictionary<MyKey, MyValue>基于的集合MyKey.KeyType.KeyType是一个枚举.

然后我将留下一个包含键值对的MyKey.KeyType = 1字典,其中,另一个字典在哪里MyKey.KeyType = 2,依此类推.

有没有一种很好的方法,比如使用Linq?

Meh*_*ari 9

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
Run Code Online (Sandbox Code Playgroud)

如果你想要一个最后用"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
Run Code Online (Sandbox Code Playgroud)