繁体   English   中英

从Dictionary C#中查找特定键

[英]Finding a specific key from a Dictionary C#

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

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

dictionaryTwo[item.Key]

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

或者,您可以使用TryGetValue:

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

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

为什么不使用索引器?

dictionaryTwo[item.Key]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM