Alex Rivera | Logout

How to combine two dictionaries without looping?

Asked 2009-04-03T07:48:45.083
50

I have two dictionaries (intersection is empty) of type <string,object> in C#. How can I copy all the contents of one Dictionary object to the other without applying a loop?

Edit
Report

2 Answers

96
var d3 = d1.Concat(d2).ToDictionary(x => x.Key, x => x.Value);
answered 2009-04-03T08:58:42.807
43

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);
}
answered 2009-04-03T08:21:53.270

Your Answer