16

我花了几个小时尝试将简单的 SQL 转换为 lambda LINQ

SELECT ID, AVG(Score) FROM myTable
GROUP BY ID

任何的想法?

4

3 回答 3

30
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 
         })
于 2013-03-29T03:25:00.410 回答
2

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。

于 2013-03-29T03:24:09.063 回答
0
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)
                }
于 2013-03-29T03:23:47.617 回答