Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping data and making aggregate calculations in C#

Tags:

c#

.net

I have something like this within a List<object> where object contains Cat, Type and Items.

Cat  | Type | Items
--------------------
 A   |  P   |  3
 A   |  Q   |  4
 A   |  R   |  2
 A   |  P   |  1
 A   |  Q   |  5
 B   |  P   |  2
 B   |  Q   |  1
 B   |  R   |  3
 B   |  P   |  9

What I want to do is calculate the average items of the types so produce something like this:

Cat  | Type | Items
--------------------
 A   |  P   |  2
 A   |  Q   |  4.5
 A   |  R   |  2
 B   |  P   |  5.5
 B   |  Q   |  3
 B   |  R   |  5

As you can see the average items are calculated for the types Whats the best way to do this?

like image 444
flammable11 Avatar asked Jan 13 '11 22:01

flammable11


1 Answers

Assuming the input is provided in a variable called list of type IEnumerable<Blah> (containing, for example, a database query result, a List<Blah>, an array, etc.etc.), and that Blah is a class with fields or properties called Cat, Type and Items:

var result = list.GroupBy(entry => new { entry.Cat, entry.Type })
                 .Select(group => new { group.Key.Cat, group.Key.Type,
                                        Items = group.Average(e => e.Items) })
like image 149
Timwi Avatar answered Sep 30 '22 19:09

Timwi