Translate SQL to lambda LINQ with GroupBy and Average

删除回忆录丶 提交于 2020-01-01 04:24:10

问题


I spend a few hours trying to translate simple SQL to lambda LINQ

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

Any idea?


回答1:


from t in myTable
group t by new {
  t.ID
} into g
select new {
  Average = g.Average(p => p.Score),
  g.Key.ID
}

or Lambda

myTable.GroupBy(t => new  {ID = t.ID})
   .Select (g => new {
            Average = g.Average (p => p.Score), 
            ID = g.Key.ID 
         })



回答2:


The equivalent in Linq-to-Objects would be something like the below.

var results = from row in myTable
              group row by row.Id into rows 
              select new 
              {
                  Id = rows.Key,
                  AverageScore = rows.Average(row => row.Score)
              };

It's only slightly different for an ORM like entity framework. Namely, you would need to go through the data context or an appropriate DbSet/ObjectSet.




回答3:


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


来源:https://stackoverflow.com/questions/15696817/translate-sql-to-lambda-linq-with-groupby-and-average

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!