查找键值对中已存在的值

Oli*_*ham 21 .net c# key-value

我在Key值对中存储字符串和int值.

var list = new List<KeyValuePair<string, int>>();
Run Code Online (Sandbox Code Playgroud)

添加时我需要检查列表中是否已存在字符串(Key),如果存在,我需要将其添加到Value而不是添加新密钥.
如何检查和添加?

Hab*_*bib 30

您可以使用Dictionary而不是List ,检查它是否包含密钥,然后将新值添加到现有密钥

int newValue = 10;
Dictionary<string, int> dictionary = new Dictionary<string, int>();
if (dictionary.ContainsKey("key"))
    dictionary["key"] = dictionary["key"] + newValue;
Run Code Online (Sandbox Code Playgroud)

  • 但另一方面,Dictionary不支持具有不同值的相同键. (5认同)

Rav*_*dag 7

使用dictonary.C#中的字典,我建议你阅读这篇文章.net中的Dictonary

Dictionary<string, int> dictionary =
        new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);
Run Code Online (Sandbox Code Playgroud)

去检查.使用ContainsKey ContainsKey

if (dictionary.ContainsKey("key"))
    dictionary["key"] = dictionary["key"] + yourValue;
Run Code Online (Sandbox Code Playgroud)


小智 7

对于任何必须使用 List 的人(对我来说就是这种情况,因为它可以完成 Dictionary 所不具备的功能),您可以使用 lambda 表达式来查看 List 是否包含 Key:

list.Any(l => l.Key == checkForKey);
Run Code Online (Sandbox Code Playgroud)


小智 5

如果需要使用列表,则必须预先列出该列表,然后查找键.简单地说,您可以使用哈希表.