0

Let's assume I have two variables which both are of type Dictionary<int, int>.

Dictionary<int, int> d1 = new Dictionary<int, int> { ... };
Dictionary<int, int> d2 = new Dictionary<int, int> { ... };

Both dictionaries could potentionally contain the same keys.

I want them to combine into a single Dictionary<int, int> combinedDictionary.

What would be an elegant way to do this?

I've tried the following:

var combinedDictionary = d1.Concat(d2.Where(x => !d1.Keys.Contains(x.Key)));

But unfortunately, when trying to return this combined variable I get the following error:

Cannot convert expression type 'System.Collections.Generic.IEnumerable>' to return type 'System.Collections.Generic.Dictionary'.

Is it possible to safely cast it like this?

return (Dictionary<int, int>) combinedDictionary;

thanks in advance!

xeraphim
  • 3,457
  • 7
  • 34
  • 74

1 Answers1

1

Concat returns an IEnumerable<KeyValuePair<TKey, TValue>>. You want to call ToDictionary to convert that into a Dictionary.

IEnumerable<KeyValuePair<int, int>> combined = d1.Concat(d2.Where(x => !d1.Keys.Contains(x.Key)));
Dictionary<int, int> result = combined.ToDictionary(x => x.Key, x => x.Value);
Amy B
  • 100,846
  • 20
  • 127
  • 174