在C#中从字典中找到特定的键

3
我正在处理一段代码,它需要比较字典中的键。如果键匹配,则需要比较值以查看它们是否相同,如果不同,则需要写入键和两个描述(第一个字典的值和第二个字典的值)。我已经了解了TryGetValue函数,但似乎并不是我所需的。有没有一种方法可以检索第二个字典中具有与第一个字典相同键的值?谢谢。
        foreach (KeyValuePair<string, string> item in dictionaryOne) 
        {
            if (dictionaryTwo.ContainsKey(item.Key))
            {
                //Compare values
                //if values differ
                //Write codes and strings in format
                //"Code: " + code + "RCT3 Description: " + rct3Description + "RCT4 Description: " + rct4Description

                if (!dictionaryTwo.ContainsValue(item.Value))
                {
                    inBoth.Add("Code: " + item.Key + " RCT3 Description: " + item.Value + " RCT4 Description: " + );
                }

            }
            else
            {
                //If key doesn't exist
                //Write code and string in same format as input file to array
                //Array contains items in RCT3 that are not in RCT4
                rct3In.Add(item.Key + " " + item.Value);
            }
        }

1
是的,TryGetValue 将完全满足你的需求。 - Erti-Chris Eelmaa
你尝试过使用 TryGetValue 吗?你能展示一下你如何调用它的例子吗?(这正是你所需要的...)。 - O. R. Mapper
我尝试使用它,但是我输入了错误的值(与下面的答案相比)。 - Jason W
2个回答

8

您可以直接通过以下方式访问第二个字典中的项目:

dictionaryTwo[item.Key]

一旦您确认存在该键的项,就可以安全地执行此操作,就像您在代码中所做的那样。

或者,您可以使用TryGetValue:

string valueInSecondDict;
if (dictionaryTwo.TryGetValue(item.Key, out valueInSecondDict)) {
    // use "valueInSecondDict" here
}

我感觉很蠢,本应该知道要使用索引器。 - Jason W

4
有没有一种方法可以从第二个字典中检索与第一个字典相同键的值?为什么不使用索引器?
dictionaryTwo[item.Key]

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