簡體   English   中英

從Dictionary C#中查找特定鍵

[英]Finding a specific key from a Dictionary C#

我有這個與我合作的代碼。 它需要比較字典中的鍵。 如果鍵匹配則需要比較值以查看它們是否相同,如果不是,我需要將鍵與兩個描述一起寫入(第一個字典的值和第二個字典的值)。 我讀過有關TryGetValue的內容,但它似乎並不是我需要的。 有沒有辦法從第二個字典中檢索具有與第一個字典中相同的鍵的值?

謝謝

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

您只需訪問第二個字典中的項目即可

dictionaryTwo[item.Key]

一旦您確認有一個帶有該密鑰的項目,就像您在代碼中所做的那樣,這是安全的。

或者,您可以使用TryGetValue:

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

有沒有辦法從第二個字典中檢索具有與第一個字典中相同的鍵的值?

為什么不使用索引器?

dictionaryTwo[item.Key]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM