Since dictionaries implement IEnumerable<KeyValuePair<TKey, TValue>>
, you can simply write:
var result = dict1
.Concat(dict2)
.Concat(dict3)
.Concat(dict4)
.Concat(dict5)
.ToDictionary(e => e.Key, e => e.Value);
This assumes that there are no duplicate keys.
If there are duplicate keys, you could get the first value for each key
result = dict1
.Concat(dict2)
.Concat(dict3)
.Concat(dict4)
.Concat(dict5)
.GroupBy(e => e.Key)
.ToDictionary(g => g.Key, g => g.First().Value);
Other variants are conceivable, like keeping the maximum/minimum value etc.
If there are duplicate keys with different values, you could also create a dictionary of value lists
Dictionary<TKey, List<TValue>> result = dict1
.Concat(dict2)
.Concat(dict3)
.Concat(dict4)
.Concat(dict5)
.GroupBy(e => e.Key, e => e.Value)
.ToDictionary(g => g.Key, v => v.ToList());
Instead of creating a List<T>
of values, you could insert them into a HashSet<T>
to only keep unique values.
If the values are always the same for duplicate keys then simply use Union
instead of Concat
:
var result = dict1
.Union(dict2)
.Union(dict3)
.Union(dict4)
.Union(dict5)
.ToDictionary(e => e.Key, e => e.Value);
Union
produces the set union of two sequences. Concat
concatenates two sequences.
Finally, you can combine the two preceding approaches and discard equal key/value pairs, but keep a list of different values per key:
Dictionary<TKey, List<TValue>> result = dict1
.Union(dict2)
.Union(dict3)
.Union(dict4)
.Union(dict5)
.GroupBy(e => e.Key, e => e.Value)
.ToDictionary(g => g.Key, v => v.ToList());
These examples show that it is important to know exactly how the input data is shaped (unique/non-unique keys and key-value-pairs) and precisely what kind of result you expect.
A different approach would be to let your different methods return lists or enumerations instead of dictionaries and merge these collections into a dictionary at the end. This would be more performing.