我想合并两个字典。尝试此操作时,我收到有关重复键的错误。如何合并具有相同键的两个字典?
class Program
{
static void Main(string[] args)
{
Dictionary<Class1.Deneme, List<string>> dict1 = new Dictionary<Class1.Deneme, List<string>>();
Dictionary<Class1.Deneme, List<string>> dict2 = new Dictionary<Class1.Deneme, List<string>>();
Dictionary<Class1.Deneme, List<string>> dict3 = new Dictionary<Class1.Deneme, List<string>>();
List<string> list1 = new List<string>() { "a", "b" };
List<string> list2 = new List<string>() { "c", "d" };
List<string> list3 = new List<string>() { "e", "f" };
List<string> list4 = new List<string>() { "g", "h" };
dict1.Add(Class1.Deneme.Buyer, list1);
dict2.Add(Class1.Deneme.Buyer, list2);
dict3 = dict1.Concat(dict2).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Console.Read();
}
}
public class Class1
{
public enum Deneme
{
Customer=1,
Buyer=2,
Supplier=3
}
}
最佳答案
怎么样
static IDictionary<TKey, TValue> Merge<TKey, TValue>(
this IDictionary<TKey, TValue> left,
IDictionary<TKey, TValue> right,
Func<TKey, TValue, TValue, TValue> valueMerger)
{
var result = new Dictionary<TKey, TValue>();
foreach(var pair in left.Concat(right))
{
if (result.ContainsKey(pair.Key))
{
result[pair.Key] = valueMerger(
pair.Key,
pair.Value,
result[pair.Key]);
continue;
}
result.Add(pair.Key, pair.Value);
}
return result;
}
因此,您需要提供一个委托来处理键重复的情况。我建议您以您的示例为例,
var dictionary1 = new Dictionary<Class1.Deneme, List<string>>();
var dictionary2 = new Dictionary<Class1.Deneme, List<string>>();
var merged = dictionary1.Merge(
dictionary2,
(key, left, right) => left.Concat(right));
还是您宁愿抛出异常?
var merged = dictionary1.Merge(
dictionary2,
(key, left, right) => throw new ArgumentException("right", ...);