jeudi 23 octobre 2014

Finding a specific key from a Dictionary C#


Vote count:

2




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. 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);
}
}


asked 7 mins ago


2 Answers



Vote count:

4




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:



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


answered 4 mins ago

Niko

16.5k


Vote count:

3





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]


answered 4 mins ago

Selman22

47.4k





Finding a specific key from a Dictionary C#

Aucun commentaire:

Enregistrer un commentaire