我花了几个小时尝试将简单的 SQL 转换为 lambda LINQ
SELECT ID, AVG(Score) FROM myTable
GROUP BY ID
任何的想法?
from t in myTable
group t by new {
t.ID
} into g
select new {
Average = g.Average(p => p.Score),
g.Key.ID
}
或拉姆达
myTable.GroupBy(t => new {ID = t.ID})
.Select (g => new {
Average = g.Average (p => p.Score),
ID = g.Key.ID
})
Linq-to-Objects 中的等价物如下所示。
var results = from row in myTable
group row by row.Id into rows
select new
{
Id = rows.Key,
AverageScore = rows.Average(row => row.Score)
};
对于类似 ORM 的实体框架来说,它只是略有不同。也就是说,您需要通过数据上下文或适当的 DbSet/ObjectSet。
var _result = from a in myTable
group a by a.ID into g
select new
{
ID = g.Key.ID,
AverageResult = g.Average(x => x.Score)
}