Home > Software engineering >  Get average of sum of grouped values with LINQ
Get average of sum of grouped values with LINQ

Time:05-14

I have an IEnumerable with fields Name(string) and Amount(ulong). I want to get a single LINQ query to group those elements by Name and then get their sum and average of that sum.

To get a sum of groupped elements I did something like this

collection.GroupBy(x => x.Name).Select(x => new { Key = x.Key, Sum = x.Sum(e => Int32.Parse(e.Amount.ToString()))});

It works perfectly fine but is there a way to now get an average of each group without making separate LINQ or method or whatever?

I've tried several ways but none of them was correct. The best I did was to get the average of every Amount :/

CodePudding user response:

You should be able to add another member to the anonymous type to return the average, similar to how you return the sum.

collection.GroupBy(x => x.Name)
    .Select(x => new { 
        Key = x.Key,
        Sum = x.Sum(e => Int32.Parse(e.Amount.ToString()),
        Avg = x.Average(e => Int32.Parse(e.Amount.ToString())
    });
  • Related