合并两个字典并删除重复的键,按值排序

5
我必须将两个字典合并为一个字典,并删除重复的条目,如果第一个字典中不存在,则添加。
 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"}

1
字典默认情况下不允许添加重复的键。 - Nisarg Shah
你有什么问题? - Jordy
我已经编辑了问题。基本上,我想合并字典(不重复项),如果第一个字典中不存在键,则将第二个字典中的项添加到第一个字典中。 - Akshay Deshpande
6个回答

6

您可以使用示例LINQ和拼接来实现您想要的效果。以下是示例代码:

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"}

感谢您的回复。这只是一个简短的回答。 - Akshay Deshpande

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;
}

原帖保留现有的值。 - Jeroen van Langen

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>,因为它按键而不是值进行排序。

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

1

我会尝试这个:

foreach(var pair in secondDict)
{
   if(!(firstDict.ContainsKey(pair.Key)))
   {
      firstDict.Add(pair.Key, pair.Value);
   }
}

这是您想要的吗?我还没有通过编译器进行测试,所以请尝试一下。


0

我不确定,您是否想将它们合并?如果是这样,您可以:

1. 创建一个 firstDict 的副本,用于设置最终结果。

2. 对于 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)

希望能对你有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接