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

C#中foreach循环内如何获取动态命名的period对应字段更新数据

解决方案

首先可以先简化周期字段名的生成逻辑,原来的Substring拼接可以直接替换为更简洁的写法,一步得到_2101这种符合你表字段格式的名称:

string fieldName = startDate.ToString("_yyMM");

接下来根据你report集合的类型,选择对应实现方式:

场景1:report是DataTable的行集合(DataRow[]/DataRowCollection)

这种场景直接用字段名索引访问即可,写法最简单:

foreach (DataRow item in report)
{
   if (Convert.ToInt32(item["Group"]) == 1)
   {
      item[fieldName] = amount; 
   }
}

场景2:report是自定义Report实体类的集合

这种情况可以用反射实现动态属性赋值,建议提前缓存属性信息避免循环内重复反射损耗性能:

// 循环外提前获取对应属性,一次获取多次使用
var periodProp = typeof(Report).GetProperty(fieldName);
if (periodProp == null)
{
    // 可自定义异常处理逻辑,避免不存在的字段导致报错
    throw new Exception($"未找到对应周期字段:{fieldName}");
}

foreach (var item in report)
{
   if (item.Group == 1)
   {
      periodProp.SetValue(item, amount);
   }
}

如果要避免每次反射的麻烦,也可以直接在Report实体类中添加索引器封装反射逻辑,后续用起来更便捷:

public class Report
{
    public int Group { get; set; }
    public decimal? _2101 { get; set; }
    public decimal? _2102 { get; set; }
    // 其他字段省略

    public object this[string fieldName]
    {
        get
        {
            var prop = typeof(Report).GetProperty(fieldName);
            return prop?.GetValue(this);
        }
        set
        {
            var prop = typeof(Report).GetProperty(fieldName);
            if (prop != null && prop.CanWrite)
            {
                prop.SetValue(this, value);
            }
        }
    }
}

// 循环内直接通过索引器赋值
foreach (var item in report)
{
   if (item.Group == 1)
   {
      item[fieldName] = amount; 
   }
}

注意事项

  • 你示例代码中写的item.Grup为拼写错误,实际应为Group,注意修正避免逻辑错误
  • 赋值前请确认amount的类型和对应周期字段的类型匹配,避免出现类型转换异常
  • 如果存在多周期循环的场景,建议把所有用到的周期字段属性提前缓存,进一步提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:18:03