[英]Finding a specific key from a Dictionary C#
I have this code I am working with. 我有这个与我合作的代码。 It needs to compare keys from a dictionary. 它需要比较字典中的键。 If the keys match then the values need to be compared to see if they are the same, if they are not I need to write the key along with both descriptions (value from first dictionary, and value from the second one). 如果键匹配则需要比较值以查看它们是否相同,如果不是,我需要将键与两个描述一起写入(第一个字典的值和第二个字典的值)。 I have read about TryGetValue, but it doesn't seem to be what I need. 我读过有关TryGetValue的内容,但它似乎并不是我需要的。 Is there a way to retrieve the value from the second dictionary that has the same key as in the first dictionary? 有没有办法从第二个字典中检索具有与第一个字典中相同的键的值?
Thank you 谢谢
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);
}
}
You can simply access the item in the second dictionary by 您只需访问第二个字典中的项目即可
dictionaryTwo[item.Key]
This is safe once you've confirmed that there is an item with that key, as you've done in your code. 一旦您确认有一个带有该密钥的项目,就像您在代码中所做的那样,这是安全的。
Alternatively, you can use TryGetValue: 或者,您可以使用TryGetValue:
string valueInSecondDict;
if (dictionaryTwo.TryGetValue(item.Key, out valueInSecondDict)) {
// use "valueInSecondDict" here
}
Is there a way to retrieve the value from the second dictionary that has the same key as in the first dictionary? 有没有办法从第二个字典中检索具有与第一个字典中相同的键的值?
Why not use the indexer ? 为什么不使用索引器?
dictionaryTwo[item.Key]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.