0

Is there a simpler way to copy/add all content of source dictionary to destination Dictionary<T1, T2> object than using one of the two options in the sample below?

Dictionary<string, int> source = new Dictionary<string, int>(),
    destination = new Dictionary<string, int>();

source.Add("Developers", 1);
source.Add("just", 2);
source.Add("wanna have", 3);
source.Add("FUN!", 4);

// Option 1 (feels like a hack):
//
source.All(delegate(KeyValuePair<string, int> p)
{
    destination.Add(p.Key, p.Value);
    return true;
});

// Option 2:
//
foreach (string k in source.Keys)
{
    destination.Add(k, source[k]);
}

What I was looking for is something like .ForEach().

RhinoDevel
  • 712
  • 1
  • 12
  • 25
  • Does Option 1 or 2 work? – Tim Schmelter Mar 17 '16 at 12:43
  • 1
    You mean like `List.ForEach`? [Be careful what you wish for..](https://blogs.msdn.microsoft.com/ericlippert/2009/05/18/foreach-vs-foreach/) – stuartd Mar 17 '16 at 12:45
  • 2
    Option 2 is about as simple as you can get. You have a loop condition, and one statement within the loop. Don't go complicating it by trying to shoehorn `ForEach`, and don't pass a delegate to a query method (`All`) that has side-effects. – D Stanley Mar 17 '16 at 12:47
  • @DStanley: Yes, that is what I thought. – RhinoDevel Mar 17 '16 at 12:48
  • See [this question](http://stackoverflow.com/questions/6050633) for some arguments for and against a `ForEach` method, and some extension methods that may work. – D Stanley Mar 17 '16 at 12:50

3 Answers3

5

Yes, you can use the constructor:

Dictionary<string, int> destination = new Dictionary<string, int>(source);

If destination is already filled and you don't want to lose them as commented i'd use this:

foreach (var kv in source)
    if (!destination.ContainsKey(kv.Key))
        destination.Add(kv.Key, kv.Value);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You can use Concat:

Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("first", 1);
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("second", 2);

dict2 = dict2.Concat(dict1).ToDictionary(k => k.Key, v => v.Value);

This of course doesn't really 'add' it to the dictionary, but replaces it by a new one. You can use Union to get rid of duplicates.

Alexander Derck
  • 13,818
  • 5
  • 54
  • 76
0
static void Main()
{
    Dictionary<string, int> source = new Dictionary<string, int>();
    Dictionary<string, int> destination = new Dictionary<string, int>();
    destination.Add("Apple", 1);
    destination.Add("Banana", 2);
    foreach (var item in destination)
    {
        source.Add(item.Key, item.Value);
    }
    foreach (var item in destination)
    {
        Console.WriteLine("Key is {0} and value is {1}", item.Key, item.Value);
    }       
}
Madhav
  • 1
  • 2