Finding a specific key from a C # dictionary
I have some code that I am working with. It must compare keys from the dictionary. If the keys are the same then the values need to be compared to make sure they are the same, if not needed I need to write the key along with both descriptions (the value from the first dictionary and the value from the second). I've read about TryGetValue, but it doesn't seem to be what I want. Is there a way to get the value from the second dictionary that has the same key as the first dictionary?
thank
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);
}
}
+3
source to share
2 answers
You can just access the element in the second dictionary
dictionaryTwo[item.Key]
It is safe if you have confirmed that there is an item with this key, as it was in your code.
Alternatively, you can use TryGetValue:
string valueInSecondDict;
if (dictionaryTwo.TryGetValue(item.Key, out valueInSecondDict)) {
// use "valueInSecondDict" here
}
+8
source to share