如何更新字典 Dictionary<string, int>
中特定键的值?
只需指向给定键的字典并分配一个新值:
myDictionary[myKey] = myNewValue;
可以通过将键作为索引访问
例如:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2
++dictionary["test"];
或 dictionary["test"]++;
但前提是字典中有一个键值为“test”的条目 - 例如:if(dictionary.ContainsKey("test")) ++dictionary["test"];
else dictionary["test"] = 1; // create entry with key "test"
您可以遵循以下方法:
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;
更新值,那么您将访问字典两次。
dic[key] = newvalue;
而不是 dic.Add(key, newValue);
。
使用 LINQ:访问键的字典并更改值
Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);
这是一种通过索引进行更新的方法,类似于 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;
}
}
这个简单的检查将做一个 upsert 即更新或创建。
if(!dictionary.TryAdd(key, val))
{
dictionary[key] = val;
}
更新 - 仅修改存在的。为了避免索引器使用的副作用: int val; if (dic.TryGetValue(key, out val)) { // 键存在 dic[key] = val; } 更新或(如果 dic 中不存在值,则添加新值) dic[key] = val;例如:d["Two"] = 2; // 添加到字典,因为 "two" 不存在 d["Two"] = 22; // 更新字典,因为 "two" 现在存在
这可能对您有用:
场景一:原始类型
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;
希望对需要帮助的人有用。
这个扩展方法允许一个匹配谓词委托作为字典键选择器,以及一个单独的委托来执行字典值替换,因此它对于所使用的键/值对的类型是完全开放的:
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);
}
不定期副业成功案例分享