How to combine two dictionaries without loops?

I have two dictionaries of type <string,object> in C #. How can I copy the entire contents of one Dictionary object to another without using a loop?

+44
collections dictionary c #
Apr 3 '09 at 7:48
source share
4 answers
 var d3 = d1.Concat(d2).ToDictionary(x => x.Key, x => x.Value); 
+87
Apr 03 '09 at 8:58
source share

You can use Concat :

 Dictionary<string, object> d1 = new Dictionary<string, object>(); d1.Add("a", new object()); d1.Add("b", new object()); Dictionary<string, object> d2 = new Dictionary<string, object>(); d2.Add("c", new object()); d2.Add("d", new object()); Dictionary<string, object> d3 = d1.Concat(d2).ToDictionary(e => e.Key, e => e.Value); foreach (var item in d3) { Console.WriteLine(item.Key); } 
+38
Apr 03 '09 at 8:21
source share

At first, this is not possible without a loop. Regardless of whether this loop is executed in a method (extensions), it still requires a loop.

I really recommend doing it manually. All other answers require the use of two extension methods (Concat - ToDictionary and SelectMany - ToDictionary) and thus loop twice. If you do this to optimize your code, it will be faster to loop over dictionary B and add it to dictionary A.

Edit: After further investigation, the Concat operation will only occur during a call to ToDictionary, but I still believe that the custom extension method will be more efficient.

If you want to reduce your code size, just create an extension method:

 public static class DictionaryExtensions { public static IDictionary<TKey,TVal> Merge<TKey,TVal>(this IDictionary<TKey,TVal> dictA, IDictionary<TKey,TVal> dictB) { IDictionary<TKey,TVal> output = new Dictionary<TKey,TVal>(dictA); foreach (KeyValuePair<TKey,TVal> pair in dictB) { // TODO: Check for collisions? output.Add(pair.Key, Pair.Value); } return output; } } 

Then you can use it by importing ('using') the DictionaryExtensions namespace and writing:

 IDictionary<string,objet> output = dictA.Merge(dictB); 

I made the method the same as immutable objects, but you can easily change it so as not to return a new dictionary and just merge with dictA.

+9
Apr 03 '09 at 8:41
source share
 var result = dictionaries.SelectMany(dict => dict) .ToDictionary(pair => pair.Key, pair => pair.Value); 
+5
Apr 03 '09 at 8:15
source share



All Articles