Is there a way of splitting a C# generic dictionary into multiple dictionaries?

c#, dictionary, linq, split

Solution

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

Problem

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?

Original source