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) {
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.
Richard Szalay Apr 03 '09 at 8:41 2009-04-03 08:41
source share