如何在LINQ查询中使用GROUP BY获取MAX行?

我正在寻找一种方式在LINQ来匹配后续SQL查询。

Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number 

真的想在这一个帮助。 上面的查询获取每个序列号的最大值,因为Group By语法Group By

  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) } 

我在LinqPad上检查过DamienG的回答。 代替

 g.Group.Max(s => s.uid) 

应该

 g.Max(s => s.uid) 

谢谢!

在方法链forms中:

 db.Serials.GroupBy(i => i.Serial_Number).Select(g => new { Serial_Number = g.Key, uid = g.Max(row => row.uid) }); 

如果你只需要这两个字段,答案是可以的,但对于一个更复杂的对象,这种方法可能是有用的:

 from x in db.Serials group x by x.Serial_Number into g orderby g.Key select g.OrderByDescending(z => z.uid) .FirstOrDefault() 

…这将避免“select新的”