【问题标题】:Simplest way to add all content of Dictionary<T1, T2> to another Dictionary<T1, T2> (equal types for key & value)?将 Dictionary<T1, T2> 的所有内容添加到另一个 Dictionary<T1, T2> 的最简单方法(键和值的类型相同)?
【发布时间】:2016-07-03 19:40:35
【问题描述】:

有没有比使用下面示例中的两个选项之一更简单的方法来将 source 字典的所有内容复制/添加到 destination Dictionary&lt;T1, T2&gt; 对象?

Dictionary<string, int> source = new Dictionary<string, int>(),
    destination = new Dictionary<string, int>();

source.Add("Developers", 1);
source.Add("just", 2);
source.Add("wanna have", 3);
source.Add("FUN!", 4);

// Option 1 (feels like a hack):
//
source.All(delegate(KeyValuePair<string, int> p)
{
    destination.Add(p.Key, p.Value);
    return true;
});

// Option 2:
//
foreach (string k in source.Keys)
{
    destination.Add(k, source[k]);
}

我正在寻找类似.ForEach() 的东西。

【问题讨论】:

  • 选项 1 或 2 有效吗?
  • 你的意思是像List.ForEachBe careful what you wish for..
  • 选项 2 非常简单。您有一个循环条件和一个循环内的语句。不要试图强加 ForEach 以使其复杂化,也不要将委托传递给具有副作用的查询方法 (All)。
  • @DStanley:是的,我就是这么想的。
  • 请参阅this question,了解支持和反对ForEach 方法的一些论据,以及一些可能有效的扩展方法。

标签: c#


【解决方案1】:

是的,您可以使用constructor

Dictionary<string, int> destination = new Dictionary<string, int>(source);

如果destination 已经被填满,并且您不想丢失它们,我会使用这个:

foreach (var kv in source)
    if (!destination.ContainsKey(kv.Key))
        destination.Add(kv.Key, kv.Value);

【讨论】:

  • 如果destination 中已经有键/值对你不想松动怎么办?
  • @RhinoDevel:这是一个不同的问题,如果有重复,那么在这种情况下,您的两个选项都将不起作用。
  • 我不想创建source 的副本,我想将source 的所有内容复制/添加到destination
  • @RhinoDevel:看看我的第二种方法。如果您想添加所有“新”,这是最简单和最有效的方法。
【解决方案2】:

你可以使用Concat:

Dictionary<string, int> dict1 = new Dictionary<string, int>();
dict1.Add("first", 1);
Dictionary<string, int> dict2 = new Dictionary<string, int>();
dict2.Add("second", 2);

dict2 = dict2.Concat(dict1).ToDictionary(k => k.Key, v => v.Value);

这当然并没有真正将它“添加”到字典中,而是用一个新的替换它。您可以使用Union 去除重复项。

【讨论】:

  • 重复键抛出异常,效率不高。
  • @TimSchmelter 最好的选择就是在 OP 的问题中使用 foreach ,但这只是一种选择。
【解决方案3】:
static void Main()
{
    Dictionary<string, int> source = new Dictionary<string, int>();
    Dictionary<string, int> destination = new Dictionary<string, int>();
    destination.Add("Apple", 1);
    destination.Add("Banana", 2);
    foreach (var item in destination)
    {
        source.Add(item.Key, item.Value);
    }
    foreach (var item in destination)
    {
        Console.WriteLine("Key is {0} and value is {1}", item.Key, item.Value);
    }       
}

【讨论】:

    猜你喜欢
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    • 2019-12-07
    • 1970-01-01
    相关资源
    最近更新 更多