开发者

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.


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


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜