GroupBy Key Based Dictionary

I have a Dictionary<string,string> that I want to group. Here are some examples of key / value pairs

 ========================== | Key | Value | ========================== | A_FirstValue | 1 | | A_SecondValue | 2 | | B_FirstValue | 1 | | B_SecondValue | 2 | ========================== 

Now I want to group it according to the first letter or word in the key before the first instance of the '_' character

So, the end result will be Dictionary<string, Dictionary<string, string>> . For the example above, the result will be:

 A -> A_FirstValue, 1 A_SecondValue, 2 B -> B_FirstValue, 1 B_SecondValue, 2 

Is it possible? Who could help me?

Thanks.

+4
source share
3 answers

Well, you could use:

 var dictionary = dictionary.GroupBy(pair => pair.Key.Substring(0, 1)) .ToDictionary(group => group.Key, group => group.ToDictionary(pair => pair.Key, pair => pair.Value)); 

Part of the group will provide you with IGrouping<string, KeyValuePair<string, string>> , and the subsequent ToDictionary convert each group of key / value pairs back to the dictionary.

EDIT: note that this will always use the first letter. For something more complicated, I would probably write a separate ExtractFirstWord(string) method and call it in the GroupBy lambda expression.

+9
source
 yourDictionary .GroupBy(g => g.Key.Substring(0, 1)) .ToDictionary(k => k.Key, v => v.ToDictionary(k1 => k1.Key, v1 => v1.Value)); 
0
source

Here is what I came up with. There should be some error handling to ensure that _ exists in the key, but you need to get started.

  var source = new Dictionary<string, int>(); source.Add("A_FirstValue", 1); source.Add("A_SecondValue", 2); source.Add("B_FirstValue", 1); source.Add("B_SecondValue", 3); var dest = new Dictionary<string, Dictionary<string, int>>(); foreach (KeyValuePair<string, int> entry in source) { string prefix = entry.Key.Split('_')[0]; if (!dest.ContainsKey(prefix)) { dest.Add(prefix, new Dictionary<string, int>()); } dest[prefix].Add(entry.Key, entry.Value); } 
0
source

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


All Articles