cca*_*oni 686
只需指定给定键的字典并指定一个新值:
myDictionary[myKey] = myNewValue;
Run Code Online (Sandbox Code Playgroud)
Ami*_*mit 187
可以通过访问密钥作为索引
例如:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary["test"] = 1;
dictionary["test"] += 1;
Console.WriteLine (dictionary["test"]); // will print 2
Run Code Online (Sandbox Code Playgroud)
max*_*rce 43
您可以遵循以下方法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您在这里获得的优势是,只需1次访问字典即可检查并获取相应密钥的值.如果您使用ContainsKey检查存在并使用更新值,dic[key] = val + newValue;那么您将访问字典两次.
小智 18
这个简单的检查将执行更新插入,即更新或创建。
if(!dictionary.TryAdd(key, val))
{
dictionary[key] = val;
}
Run Code Online (Sandbox Code Playgroud)
INT*_*24h 13
使用LINQ:访问密钥的字典并更改值
Dictionary<string, int> dict = new Dictionary<string, int>();
dict = dict.ToDictionary(kvp => kvp.Key, kvp => kvp.Value + 1);
Run Code Online (Sandbox Code Playgroud)
这是一种通过索引更新的方式,就像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;
}
}
Run Code Online (Sandbox Code Playgroud)