How do I get the MAX row with a GROUP BY in LINQ query?
using (DataContext dc = new DataContext())
{
var q = from t in dc.TableTests
group t by t.SerialNumber
into g
select new
{
SerialNumber = g.Key,
uid = (from t2 in g select t2.uid).Max()
};
}
var q = from s in db.Serials
group s by s.Serial_Number into g
select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }
In methods chain form:
db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
{
Serial_Number = g.Key,
uid = g.Max(row => row.uid)
});
I've checked DamienG's answer in LinqPad. Instead of
g.Group.Max(s => s.uid)
should be
g.Max(s => s.uid)
Thank you!