Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate SQL to lambda LINQ with GroupBy and Average

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

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

Any idea?

like image 371
Yuri Avatar asked Mar 29 '13 03:03

Yuri


1 Answers

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 
         })
like image 116
spajce Avatar answered Oct 20 '22 17:10

spajce