Translate SQL to lambda LINQ with GroupBy and Average

前端 未结 3 1965
心在旅途
心在旅途 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:35
    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 
             })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-13 13:38
    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)
                    }
    
    0 讨论(0)
提交回复
热议问题