Translate SQL to lambda LINQ with GroupBy and Average

前端 未结 3 1966
心在旅途
心在旅途 2021-02-13 13:14

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

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

Any idea?

3条回答
  •  再見小時候
    2021-02-13 13:36

    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.

提交回复
热议问题