【问题标题】:Dictionary Union to dictionary? [duplicate]字典联合到字典? [复制]
【发布时间】:2013-01-24 07:57:36
【问题描述】:

在我的代码中有一行

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

这感觉很奇怪,因为我很可能会经常这样做。没有.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);
        }
    }
}

【问题讨论】:

标签: c# .net linq


【解决方案1】:

使用“直接”Union 的问题在于它不会将字典解释为字典;它将字典解释为IEnumerable&lt;KeyValyePair&lt;K,V&gt;&gt;。这就是为什么您需要最后的ToDictionary 步骤。

如果您的字典没有重复键,这应该会更快:

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

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

【讨论】:

  • 它们确实具有相同的键,但它们具有相同的值。我也试图摆脱 ToDictionary 步骤。但是Concat看起来不错
  • 我正在使用 Concat,它不会因两个具有相同键的字典而中断。
猜你喜欢
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
相关资源
最近更新 更多