字典联盟到字典?

Bru*_*ode 2 .net c# linq

在我的代码中我有这条线

var d3 = d.Union(d2).ToDictionary(s => s.Key, s => s.Value);
Run Code Online (Sandbox Code Playgroud)

这感觉很奇怪,因为我很可能会这么做.没有.ToDictionary().如何将字典联合起来并将其保存为字典?

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 12

使用"笔直"的问题Union在于它不会将字典解释为字典; 它将字典解释为IEnumerable<KeyValyePair<K,V>>.这就是你需要最后ToDictionary一步的原因.

如果您的词典没有重复键,这应该更快一点:

var d3 = d.Concat(d2).ToDictionary(s => s.Key, s => s.Value);
Run Code Online (Sandbox Code Playgroud)

请注意,Union如果两个字典包含具有不同值的相同键,则该方法也会中断.Concat如果字典包含相同的键,即使它对应于相同的值,也会中断.