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

C#使用Linq对IEnumerable集合按CsId分组求和报错如何解决

错误原因

原有代码报错有两个核心问题:

  • debtRank.Select(h => ...) 中遍历得到的 h 是单个 CapStackTrancheDTO 实例,Sum 是 IEnumerable 集合的扩展方法,不可直接作用于单个对象
  • 代码中写的 CSTotCommit 大小写与类定义的属性 CsTotCommit 不一致,修复时需注意拼写匹配

正确实现

需求为按CsId分组后对CsTotCommit求和,将原有的Select替换为GroupBy分组操作即可:

匿名类型返回写法

var debtSum = debtRank
    .GroupBy(h => h.CsId)
    .Select(g => new
    {
        CsId = g.Key,
        CsTotCommit = g.Sum(x => x.CsTotCommit)
    });

强类型返回写法

如果需要返回IEnumerable<CapStackTrancheDTO>类型,调整为:

IEnumerable<CapStackTrancheDTO> debtSum = debtRank
    .GroupBy(h => h.CsId)
    .Select(g => new CapStackTrancheDTO
    {
        CsId = g.Key,
        CsTotCommit = g.Sum(x => x.CsTotCommit)
        // 其他字段按需补充赋值即可
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:54:03