如何更新值为一个特定的关键字在字典字典<字符串,int>?


当前回答

更新-修改只存在。为了避免使用索引器的副作用: int val; 如果(dic)。TryGetValue(key, out val)) { // key存在 Dic [key] = val; } 更新或(如果dic中不存在值,则添加新值) Dic [key] = val; 例如: d["Two"] = 2;//添加到字典中,因为“2”不存在 d["Two"] = 22;//更新字典,因为“two”现在存在

其他回答

你也可以使用这个方法:

Dictionary<int,int> myDic = new();
if (myDic.ContainsKey(1))
{
    myDic[1] = 1234; // or use += to update it 
}

或按值:

if (myDic.ContainsValue(1))
{
    //do something ... 
}

这个简单的检查将执行upsert,即更新或创建。

if(!dictionary.TryAdd(key, val))
{
    dictionary[key] = val;
}

这里有一种通过索引进行更新的方法,就像foo[x] = 9,其中x是键,9是值

var views = new Dictionary<string, bool>();

foreach (var g in grantMasks)
{
    string m = g.ToString();
    for (int i = 0; i <= m.Length; i++)
    {
        views[views.ElementAt(i).Key] = m[i].Equals('1') ? true : false;
    }
}

你可以这样做:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

你在这里得到的好处是,你检查并在访问字典的1次访问中获得相应的键值。 如果使用ContainsKey检查是否存在,并使用dic[key] = val + newValue更新值;然后访问字典两次。

使用LINQ:访问字典键并更改值

Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);