Home > front end >  Getting System.OverflowException using GroupBy and anonymous class
Getting System.OverflowException using GroupBy and anonymous class

Time:11-11

There is a custom class A with properties Name and Amount

There is a nested List of iterations of List A.

To get each unique A and its total amount, count etc. I use following code: `

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);            
        }

`The problem is, if nested list count is over about 3 millions iterations I get System.OverflowException: 'Arithmetic operation resulted in an overflow.'

Amount, Min and Max for sure can't exceed int.MaxValue with just 3 million iterations, I'm not sure what causing the problem.

I can workaround the problem by creating a unique list of A from nested list

var uniqueAList = NestedListofA.SelectMany(list => list).DistinctBy(a => a.Name).ToList();

and then use nested foreach to get the same statistic but the code is larger and slower

I tried to explicitly convert anonymous class properties to long to be sure the problem is not related to it but it didn't help

UPDATE: With the following fix the code is working:

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

Thanks to user @vivek nuna

CodePudding user response:

you have to check the generated query. In your case SUM is overflowing. So you can comment on the line Amount = a.Sum(a => a.Amount), if it's not required.

So declare the Amount as long and caste it is long before assigning it to Amount like Amount = a.Sum(a => (long)a.Amount

CodePudding user response:

Thanks to user @vivek nuna the problem is now solved:

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

  •  Tags:  
  • c#
  • Related