5

In my code I have the line

var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value);

This feels odd because its likely I'll do this a lot. There is no .ToDictionary(). How do I union a dictionary and keep it as a dictionary?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<Tuple<int, string>>();
            list.Add(new Tuple<int, string>(1, "a"));
            list.Add(new Tuple<int, string>(3, "b"));
            list.Add(new Tuple<int, string>(9, "c"));
            var d = list.ToDictionary(
                s => s.Item1, 
                s => s.Item2);
            list.RemoveAt(2);
            var d2 = list.ToDictionary(
                s => s.Item1,
                s => s.Item2);
            d2[5] = "z";
            var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value);
        }
    }
}
BruteCode
  • 1,143
  • 7
  • 16
  • 22

1 Answers1

17

The problem with using the "straight" Union is that it does not interpret the dictionaries as dictionaries; it interprets dictionaries as IEnumerable<KeyValyePair<K,V>>. That is why you need that final ToDictionary step.

If your dictionaries do not have duplicate keys, this should work a little faster:

var d3 = d.Concat(d2).ToDictionary(s => s.Key, s => s.Value);

Note that the Union method will break too if the two dictionaries contain the same key with different values. Concat will break if the dictionaries contain the same key even if it corresponds to the same value.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • They do have the same keys but they have the same values. Also I was trying to get rid of the ToDictionary step. But Concat looks nice – BruteCode Feb 08 '13 at 14:51
  • I'm using Concat and it doesn't break with two dictionaries having the same key. – Gonçalo Feb 27 '19 at 10:32