Dictionary<T1,T2>在C#中合并2个或更多字典()的最佳方法是什么?(像LINQ这样的3.0功能很好).
我正在考虑一种方法签名:
public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);
Run Code Online (Sandbox Code Playgroud)
要么
public static Dictionary<TKey,TValue>
Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);
Run Code Online (Sandbox Code Playgroud)
编辑:从JaredPar和Jon Skeet得到一个很酷的解决方案,但我正在考虑处理重复键的东西.在发生碰撞的情况下,只要它是一致的,将哪个值保存到dict并不重要.
我的问题被标记为这个问题的可能重复:如何在没有循环的情况下组合两个词典?
我相信我的问题是不同的,因为我问的是如何以特定的方式组合两个词典:我希望Dictionary1中的所有项目加上Dictionary2中不存在的所有项目(即密钥不存在).
我有两个这样的词典:
var d1 = new Dictionary<string,object>();
var d2 = new Dictionary<string,object>();
d1["a"] = 1;
d1["b"] = 2;
d1["c"] = 3;
d2["a"] = 11;
d2["e"] = 12;
d2["c"] = 13;
Run Code Online (Sandbox Code Playgroud)
我想将它们组合成一个新的词典(从技术上讲,它不必是一个字典,它可能只是一个序列KeyValuePairs),以便输出包含所有KeyValuePairs来自d1和只有KeyValuePairs,d2其Key不会出现在d1.
概念:
var d3 = d1.Concat(d2.Except(d1))
Run Code Online (Sandbox Code Playgroud)
但这给了我d1和d2的所有元素.
似乎它应该是显而易见的,但我必须遗漏一些东西.
我有一个帮助器,通过连接像这样的方法将两个或多个IDictionary<TKey, TValue>对象合并为一个:IDictionary<TKey, string>TValueToString()
public class DictionaryHelper<TKey, TValue>
{
public static IDictionary<TKey, string> MergeDictionaries<TKey, TValue>(params IDictionary<TKey, TValue>[] dictionaries) where TValue : class
{
var returnValue = new Dictionary<TKey, string>();
foreach (var dictionary in dictionaries)
{
foreach (var kvp in dictionary)
{
if (returnValue.ContainsKey(kvp.Key))
{
returnValue[kvp.Key] += kvp.Value.ToString();
}
else
{
returnValue[kvp.Key] = kvp.Value.ToString();
}
}
}
return returnValue;
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这很容易阅读,但似乎应该有一种更有效的方法来实现这一点.在那儿?