Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting System.OverflowException using GroupBy and anonymous class

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:
`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading