How to update the value stored in Dictionary in C#?
如何更新字典
只需指向给定键的字典并分配一个新值:
1 | myDictionary[myKey] = myNewValue; |
可以将密钥作为索引访问
例如:
1 2 3 4 | Dictionary<string, int> dictionary = new Dictionary<string, int>(); dictionary["test"] = 1; dictionary["test"] += 1; Console.WriteLine (dictionary["test"]); // will print 2 |
您可以遵循以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); } } |
您在这里得到的优势是,您只需访问字典一次,就可以检查并获取相应键的值。如果使用
对键使用linq:access to dictionary并更改值
1 2 | Dictionary<string, int> dict = new Dictionary<string, int>(); dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1); |
这里有一种通过类似于
1 2 3 4 5 6 7 8 9 10 | 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; } } |
这可能对您有用:
场景1:基本类型
1 2 3 4 5 6 7 8 | 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.Where(kvp=>kvp.Key==keyToMatchInDict).FirstOrDefault().Value ==newValToAdd; //or you can do operations such as ...Value+=newValToAdd; |
场景2:我用于列表作为值的方法
1 2 3 4 5 6 7 8 | 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.Where(kvp=>kvp.Key==keyToMatch).FirstOrDefault().Value.Add(objInValueListToAdd); |
希望对需要帮助的人有用。