简体   繁体   中英

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

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
}

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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