Translate SQL to lambda LINQ with GroupBy and Average

Yuri picture Yuri · Mar 29, 2013 · Viewed 16.7k times · Source

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

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

Any idea?

Answer

spajce picture spajce · Mar 29, 2013
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 
         })