2011-03-15 83 views
6

我有一個數據的表格類似如下:C#的LINQ平均

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

我希望以一個表作爲這樣的:

Group TimePoint AverageValue 
    1   0   2 
    1   1   4 

編輯:數據是一個數據表。

任何人有任何想法如何可以用LINQ或其他方式做到這一點?

謝謝。

+3

你是如何存儲數據的?一個'列表'? 'DataTable'?什麼? – thecoop 2011-03-15 15:04:30

+0

嗨,這是一個數據表。 – 2011-03-15 15:05:48

回答

22

您需要執行組通過

你需要的LINQ是一樣的東西:

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

更多LINQ的樣本,我極力推薦101 Linq示例頁面 - http://msdn.microsoft.com/en-us/vcsharp/aa336747#avgGrouped

+0

完美謝謝。 – 2011-03-15 15:20:43

2

你可以這樣做:

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

假設類似如下:

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

這裏有一個更加面向功能的方法(我喜歡它的方式)。第一行不會編譯,所以請用數據填寫。

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