Jason W
Jason W

Reputation: 738

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

Upvotes: 3

Views: 265

Answers (2)

Niko
Niko

Reputation: 26730

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
}

Upvotes: 8

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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]

Upvotes: 4

Related Questions