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


当前回答

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

其他回答

这可能对你有用:

场景1:基本类型

string keyToMatchInDict = "x";
int newValToAdd = 1;
Dictionary<string,int> dictToUpdate = new Dictionary<string,int>{"x",1};

if(!dictToUpdate.ContainsKey(keyToMatchInDict))
   dictToUpdate.Add(keyToMatchInDict ,newValToAdd );
else
   dictToUpdate[keyToMatchInDict] = newValToAdd; //or you can do operations such as ...dictToUpdate[keyToMatchInDict] += newValToAdd;

场景2:我用于List as Value的方法

int keyToMatch = 1;
AnyObject objInValueListToAdd = new AnyObject("something for the Ctor")
Dictionary<int,List<AnyObject> dictToUpdate = new Dictionary<int,List<AnyObject>(); //imagine this dict got initialized before with valid Keys and Values...

if(!dictToUpdate.ContainsKey(keyToMatch))
   dictToUpdate.Add(keyToMatch,new List<AnyObject>{objInValueListToAdd});
else
   dictToUpdate[keyToMatch] = objInValueListToAdd;

希望对需要帮助的人有用。

你可以这样做:

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更新值;然后访问字典两次。

这里有一种通过索引进行更新的方法,就像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;
    }
}

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

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

这个扩展方法允许一个匹配谓词委托作为字典键选择器,和一个单独的委托来执行字典值替换,所以它对所使用的键/值对的类型完全开放:

public static void UpdateAll<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Func<TKey, TValue, bool> matchPredicate, Func<TValue, TValue> updatePredicate)
{
  var keys = dictionary.Keys.Where(k => matchPredicate(k, dictionary[k])).ToList();
  foreach (var key in keys)
  {
    dictionary[key] = updatePredicate(dictionary[key]);
  }
}

使用示例:

    Dictionary<int, string> dict = new Dictionary<int, string>();
    dict.Add(1, "One");
    dict.Add(2, "Two");
    dict.Add(3, "Three");

    //Before
    foreach(var kvp in dict){
      Console.WriteLine(kvp.Value);
    }

    dict.UpdateAll(
        matchPredicate: (k, v) => k >= 2, //Update any dictionary value where the key is >= 2
        updatePredicate: (v) => v = v + " is greater than One"
      );

    //After
    foreach(var kvp in dict){
      Console.WriteLine(kvp.Value);
    }