合并两个词典并删除重复键并按值排序

时间:2013-08-08 10:22:09

标签: c# dictionary

我必须将两个字典合并为一个字典,删除重复的条目,如果第一个字典中没有,则添加。

 Dictionary<int, string> firstDict = new Dictionary<int, string>();
 firstDict.Add(1, "X");
 firstDict.Add(2, "B");

 Dictionary<int, string> secondDict = new Dictionary<int, string>();
 secondDict.Add(1, "M");
 secondDict.Add(4, "A");

结果应该是这样的:

{4, "A"}
{2, "B"}
{1, "X"}

6 个答案:

答案 0 :(得分:4)

您可以使用带有示例LINQ的Concat来实现您想要的效果。这是:

Dictionary<int, string> result = 
   firstDict.Concat(secondDict.Where(kvp => !firstDict.ContainsKey(kvp.Key)))
            .OrderBy(c=>c.Value)
            .ToDictionary(c => c.Key, c => c.Value);

结果是:

{4, "A"}
{2, "B"}
{1, "X"}

答案 1 :(得分:1)

试试这个:

foreach (var item in firstDict)
{
    secondDict[item.Key] = item.Value;
}

<强>更新

如果要保留初始值,请复制secondDict:

Dictionary<int, string> resultDict = new Dictionary<int, string>(secondDict);
foreach (var item in firstDict)
{
    resultDict[item.Key] = item.Value;
}

答案 2 :(得分:1)

你会做这样的事情:

var result = firstDict;
foreach(var newitem in secondDict.Where(x => !firstDict.ContainsKey(x.Key)))
    result.Add(newItem);

var sortedResult = result.OrderBy(x => x.Value);

请注意,result仍然是字典但未排序,而sortedResult已排序但不再是字典,因为字典中的项目顺序未定义。您也不能使用SortedDictionary<TKey, TValue>,因为它按键排序,而不是值。

答案 3 :(得分:1)

foreach (int key in secondDict.Keys)
{
    if (!firstDict.ContainsKey(key))
    firstDict.Add(key, secondDict[key]);
}

答案 4 :(得分:0)

我不确定,你想合并它们吗? 如果是这样,你能否:

第一。创建firstDict的副本,其中将设置最终结果。

第二。对于secondDict中的每个键:

1. Check if key exists in firstDict.

1.1. If it does exist(we want to keep the current result): do not do anything(sorry I miss read the result earlier)

1.2. If it doesn't exist then insert it as is(key-value from secondDict into firstDict)

希望它有所帮助!

答案 5 :(得分:0)

我会试试这个:

foreach(var pair in secondDict)
{
   if(!(firstDict.ContainsKey(pair.Key)))
   {
      firstDict.Add(pair.Key, pair.Value);
   }
}
这是你想要的吗?我还没有通过编译器对它进行测试,所以试一试。

相关问题