我有一个表格,其数据类似于以下内容:
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或其他方式完成此操作?
感谢。
答案 0 :(得分: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
答案 1 :(得分: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),
}
);
答案 2 :(得分: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)
};
答案 3 :(得分: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)
};