从字典C#中查找特定密钥

本文关键字:密钥 查找 字典 | 更新日期: 2023-09-27 18:27:31

我正在处理这段代码。它需要比较字典中的关键字。如果键匹配,则需要比较这些值以查看它们是否相同,如果不相同,我需要将键与两个描述一起编写(第一个字典中的值和第二个字典的值)。我读过关于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);
            }
        }

从字典C#中查找特定密钥

您可以简单地通过访问第二个字典中的项目

dictionaryTwo[item.Key]

一旦您确认存在具有该密钥的项目,这是安全的,就像您在代码中所做的那样。

或者,您可以使用TryGetValue:

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

有没有办法从第二个字典中检索与第一个字典具有相同关键字的值?

为什么不使用索引器?

dictionaryTwo[item.Key]