从Dictionary C#中查找特定键

Jas*_*n W 3 c# dictionary

我有这个与我合作的代码.它需要比较字典中的键.如果键匹配则需要比较值以查看它们是否相同,如果不是,我需要将键与两个描述一起写入(第一个字典的值和第二个字典的值).我读过有关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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

Nik*_*iko 8

您只需访问第二个字典中的项目即可

dictionaryTwo[item.Key]
Run Code Online (Sandbox Code Playgroud)

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

或者,您可以使用TryGetValue:

string valueInSecondDict;
if (dictionaryTwo.TryGetValue(item.Key, out valueInSecondDict)) {
    // use "valueInSecondDict" here
}
Run Code Online (Sandbox Code Playgroud)