Csharp/C#教程:如何在c#中更新字典中键的值?分享


如何在c#中更新字典中键的值?

我在c#中有以下代码,基本上它是一个带有一些键及其值的简单字典。

Dictionary dictionary = new Dictionary(); dictionary.Add("cat", 2); dictionary.Add("dog", 1); dictionary.Add("llama", 0); dictionary.Add("iguana", -1); 

我想用新值5更新关键’cat’。
我怎么能这样做?

你试过吗?

 dictionary["cat"] = 5; 

?

更新

 dictionary["cat"] = 5+2; dictionary["cat"] = dictionary["cat"]+2; dictionary["cat"] += 2; 

小心不存在的键 ?

尝试使用此简单函数添加字典项(如果它不存在)或更新它存在时:

  public void AddOrUpdateDictionaryEntry(string key, int value) { if (dict.ContainsKey(key)) { dict[key] = value; } else { dict.Add(key, value); } } 

这与dict [key] = value相同。

只需使用索引器并直接更新:

 dictionary["cat"] = 3 

字典是键值对。 抓住钥匙

 dic["cat"] 

并指定它的值

上述就是C#学习教程:如何在c#中更新字典中键的值?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 dic["cat"] = 5 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1015699.html

(0)
上一篇 2021年12月31日
下一篇 2021年12月31日

精彩推荐