You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#的Dictionary<string, int>中对存储的整数值执行减法操作

C# Dictionary遍历修改值解决方案

问题根因

  • KeyValuePair<string, int>是值类型,foreach循环中获取到的迭代元素是字典存储内容的副本,直接修改i.Value不会同步到原字典
  • myDictionary[i] -= 1写法类型不匹配:字典索引器要求传入string类型的键,你传入的是完整KeyValuePair对象,因此触发编译报错

可用实现方案

方案1:全版本兼容通用写法(推荐日常开发使用)

直接遍历字典的键集合,通过键索引定位到对应值修改即可:

foreach (string key in myDictionary.Keys)
{
    // 可在此处添加过滤逻辑,仅对符合要求的批次修改数量
    myDictionary[key] -= 1;
}

注意:如果循环中需要对字典做增/删元素操作,需要先将Key集合转为独立列表再遍历,避免迭代器失效:foreach (string key in myDictionary.Keys.ToList())

方案2:高性能优化写法(适用于.NET Core 3.0+ / .NET 5+ 版本)

如果需要避免每次通过Key查找的性能损耗,可以使用CollectionsMarshal直接获取值的引用修改:

using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

foreach (string key in myDictionary.Keys)
{
    ref int value = ref CollectionsMarshal.GetValueRefOrNullRef(myDictionary, key);
    if (!Unsafe.IsNullRef(ref value))
    {
        value--;
    }
}

内容的提问来源于stack exchange,提问作者Las Sincas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 12:39:01