我在LINQ中寻找一种方法来匹配后面的SQL查询.
Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number
真的在寻找这方面的一些帮助.由于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) }
在方法链形式:
db.Serials.GroupBy(i => i.Serial_Number).Select(g => new { Serial_Number = g.Key, uid = g.Max(row => row.uid) });
我已经检查过DamienG在LinqPad中的答案.代替
g.Group.Max(s => s.uid)
应该
g.Max(s => s.uid)
谢谢!
如果您只需要这两个字段,答案就可以了,但对于更复杂的对象,这种方法可能很有用:
from x in db.Serials group x by x.Serial_Number into g orderby g.Key select g.OrderByDescending(z => z.uid) .FirstOrDefault()
...这将避免"选择新"