Is there a way to split a C # dictionary in multiple dictionaries?

I have a C # Dictionary<MyKey, MyValue> , and I want to break it into a Dictionary<MyKey, MyValue> based on MyKey.KeyType . KeyType is an enumeration.

Then I would have left a dictionary containing key-value pairs, where MyKey.KeyType = 1 and another dictionary, where MyKey.KeyType = 2 , etc.

Is there a good way to do this, for example using Linq?

+4
source share
6 answers
 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 need a dictionary of dictionaries under the key "KeyType" at 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 
+8
source

I suppose the following will work?

 dictionary .GroupBy(pair => pair.Key.KeyType) .Select(group => group.ToDictionary(pair => pair.Key, pair => pair.Value); 
+1
source

So, do you really want a variable of type IDictionary<MyKey, IList<MyValue>> ?

0
source

You can simply 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); } 
0
source

If you just do not want to have separate collections:

 Dictionary myKeyTypeColl<KeyType, Dictionary<MyKey, KeyVal>> 
0
source
 Dictionary <int,string> sports; sports=new Dictionary<int,string>(); sports.add(0,"Cricket"); sports.add(1,"Hockey"); sports.add(2,"Badminton"); sports.add(3,"Tennis"); sports.add(4,"Chess"); sports.add(5,"Football"); foreach(var spr in sports) console.WriteLine("Keu {0} and value {1}",spr.key,spr.value); 

output:

 Key 0 and value Cricket Key 1 and value Hockey Key 2 and value Badminton Key 3 and value Tennis Key 4 and value Chess Key 5 and value Football 
0
source

Source: https://habr.com/ru/post/987039/


All Articles