Darren Young
Darren Young

Reputation: 11090

C# Linq Average

I have a table with data similar to below:

Group    TimePoint    Value
  1          0          1
  1          0          2
  1          0          3
  1          1          3
  1          1          5

I want to project a table as such:

Group    TimePoint   AverageValue
  1          0            2
  1          1            4

EDIT: The data is in a datatable.

Anybody any ideas how this can be done with LINQ or otherwise?

Thanks.

Upvotes: 6

Views: 18035

Answers (4)

Stuart
Stuart

Reputation: 66882

You need to perform Group By

The linq you need is something like:

var query = from item in inputTable
            group item by new { Group = item.Group, TimePoint = item.TimePoint } into grouped
            select new
            {
                Group = grouped.Key.Group,
                TimePoint = grouped.Key.TimePoint,
                AverageValue = grouped.Average(x => x.Value)
            } ;

For more Linq samples, I highly recommend the 101 Linq samples page - http://msdn.microsoft.com/en-us/vcsharp/aa336747#avgGrouped

Upvotes: 21

John Fisher
John Fisher

Reputation: 22721

Here's a more function-oriented approach (the way I prefer it). The first line won't compile, so fill it in with your data instead.

var items = new[] { new { Group = 1, TimePoint = 0, Value = 1} ... };
var answer = items.GroupBy(x => new { TimePoint = x.TimePoint, Group = x.Group })
                  .Select(x => new { 
                                     Group = x.Key.Group,
                                     TimePoint = x.Key.TimePoint,
                                     AverageValue = x.Average(y => y.Value),
                                   }
                  );

Upvotes: 4

Femaref
Femaref

Reputation: 61437

Assuming a class like this:

public class Record
{
  public int Group {get;set;}
  public int TimePoint {get;set;}
  public int Value {get;set;}
}

var groupAverage = from r in records
                   group r by new { r.Group, r.TimePoint } into groups
                   select new
                          {
                            Group = groups.Key.Group,
                            TimePoint = groups.Key.TimePoint,
                            AverageValue = groups.Average(rec => rec.Value)
                          };

Upvotes: 1

Ani
Ani

Reputation: 113402

You can do:

IEnumerable<MyClass> table = ...

var query = from item in table
            group item by new { item.Group, item.TimePoint } into g
            select new
            {
                g.Key.Group,
                g.Key.TimePoint,
                AverageValue = g.Average(i => i.Value)
            };

Upvotes: 2

Related Questions