Combining 3 dictionaries into one dictionary

I have the following Dictionary<string,string> dict1 has 3 items "A"="1.1" "B"="2.1" "C"="3.1" Dictionary<string,string> dict2 has 3 items "A"="1.2" "B"="2.2" "C"="3.2" Dictionary<string,string> dict2 has 3 items "A"="1.3" "B"="2.3" "C"="3.3" I want a final Dict dictFinal which is of type Dictionary<string,string[]> "A"="1.1,1.2,1.3" "B"="2.1,2.2,2.3" "C"="3.1,3.2,3.3" 
+4
source share
3 answers

Given similar keys, provide a set of all dictionaries and use SelectMany to handle the dynamic number of array elements:

 var dictionaries = new[] { dict1, dict2, dict3 }; var result = dictionaries.SelectMany(dict => dict) .GroupBy(o => o.Key) .ToDictionary(g => g.Key, g => g.Select(o => o.Value).ToArray()); 

The dictionaries type may not be a List<T> array, as indicated above. The important thing is that you group them together in a collection so that LINQ is above them.

+3
source

Assuming all 3 dictionaries have the same keys, the following should be done:

 var d1 = new Dictionary<string, string>() { {"A", "1.1"}, {"B", "2.1"}, {"C", "3.1"} }; var d2 = new Dictionary<string, string>() { {"A", "1.2"}, {"B", "2.2"}, {"C", "3.2"} }; var d3 = new Dictionary<string, string>() { {"A", "1.3"}, {"B", "2.3"}, {"C", "3.3"} }; var result = d1.Keys.ToDictionary(k => k, v => new[] {d1[v], d2[v], d3[v]}); 
+1
source

Assuming everyone has the same keys, the most direct way forward is:

 Dictionary<string,string[]> result = new Dictionary<string,string[]>(); foreach(var key in dict1.Keys) { result[key] = new string[]{dict1[key], dict2[key], dict3[key]}; } 
0
source

All Articles