如何更新值为一个特定的关键字在字典字典<字符串,int>?
当前回答
这个扩展方法允许一个匹配谓词委托作为字典键选择器,和一个单独的委托来执行字典值替换,所以它对所使用的键/值对的类型完全开放:
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);
}
其他回答
只需指向字典中给定的键并赋一个新值:
myDictionary[myKey] = myNewValue;
这个简单的检查将执行upsert,即更新或创建。
if(!dictionary.TryAdd(key, val))
{
dictionary[key] = val;
}
你也可以使用这个方法:
Dictionary<int,int> myDic = new();
if (myDic.ContainsKey(1))
{
myDic[1] = 1234; // or use += to update it
}
或按值:
if (myDic.ContainsValue(1))
{
//do something ...
}
你可以这样做:
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更新值;然后访问字典两次。
更新-修改只存在。为了避免使用索引器的副作用: int val; 如果(dic)。TryGetValue(key, out val)) { // key存在 Dic [key] = val; } 更新或(如果dic中不存在值,则添加新值) Dic [key] = val; 例如: d["Two"] = 2;//添加到字典中,因为“2”不存在 d["Two"] = 22;//更新字典,因为“two”现在存在
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何合并字典的字典?
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- Swift:声明一个空字典
- 将JSON字符串转换为HashMap
- 如何在Python中逐行打印字典?
- c#线程安全快速(est)计数器