views:

257

answers:

5

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?

+7  A: 
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
Mehrdad Afshari
+1  A: 

I believe the following will work?

dictionary
    .GroupBy(pair => pair.Key.KeyType)
    .Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value);
280Z28
A: 

So you're actually wanting a variable of type IDictionary<MyKey, IList<MyValue>>?

Unsliced
A: 

You could just use the GroupBy Linq function:

            var dict = new Dictionary<Key, string>
                   {
                       { new Key { KeyType = KeyTypes.KeyTypeA }, "keytype A" },
                       { new Key { KeyType = KeyTypes.KeyTypeB }, "keytype B" },
                       { new Key { KeyType = KeyTypes.KeyTypeC }, "keytype C" }
                   };

        var groupedDict = dict.GroupBy(kvp => kvp.Key.KeyType);

        foreach(var item in groupedDict)
        {
            Console.WriteLine("Grouping for: {0}", item.Key);
            foreach(var d in item)
                Console.WriteLine(d.Value);
        }
Venr
A: 

Unless you just want to have separate collections:

Dictionary myKeyTypeColl<KeyType, Dictionary<MyKey, KeyVal>>
dboarman