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

使用GroupBy与匿名类时触发System.OverflowException异常

嵌套集合统计时的OverflowException异常处理

场景与原代码

自定义类class A包含Name和Amount属性,现有一个嵌套的List<A>集合,需统计每个唯一Name对应的总数、总金额、最值等,初始实现代码如下:

public void GetStatistic()
{
    var result = NestedListofListA.SelectMany(iteration => iteration)
        .GroupBy(a => a.Name)
        .Select(a => new
        {
            a.Key,
            Count = a.Count(),
            Amount = a.Sum(a => a.Amount),
            Min = a.Min(a => a.Amount),
            Max = a.Max(a => a.Amount)
        })
        .OrderBy(a => a.Key);            
}

问题描述

当嵌套集合的迭代次数超过约300万时,程序抛出以下异常:

System.OverflowException: 'Arithmetic operation resulted in an overflow.'

已确认单条Amount、Min和Max的值均未超过int.MaxValue,但无法定位异常原因。曾尝试通过生成唯一A列表加嵌套foreach的方式规避问题,但代码冗余且性能较差;尝试将匿名类属性显式转为long也未解决异常。

解决方法

通过修改Sum方法的参数,将Amount先转为long类型再执行求和操作,成功解决了溢出问题。修改后的核心代码片段:

Amount = a.Sum(a => (long)a.Amount)

修改后的完整代码:

public void GetStatistic()
{
    var result = NestedListofListA.SelectMany(iteration => iteration)
        .GroupBy(a => a.Name)
        .Select(a => new
        {
            a.Key,
            Count = a.Count(),
            Amount = a.Sum(a => (long)a.Amount),
            Min = a.Min(a => a.Amount),
            Max = a.Max(a => a.Amount)
        })
        .OrderBy(a => a.Key);            
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:55:21