我在LINQ中寻找一种匹配后续SQL查询的方法。
Select max(uid) as uid, Serial_Number from Table Group BY Serial_Number
真的在寻找这方面的一些帮助。由于Group By
语法,上面的查询获取每个序列号的最大值。
答案 0 :(得分:83)
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()
};
}
答案 1 :(得分:63)
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) }
答案 2 :(得分:23)
以方法链形式:
db.Serials.GroupBy(i => i.Serial_Number).Select(g => new
{
Serial_Number = g.Key,
uid = g.Max(row => row.uid)
});
答案 3 :(得分:22)
答案 4 :(得分:8)
如果您只需要这两个字段,答案就可以了,但对于更复杂的对象,这种方法可能很有用:
from x in db.Serials
group x by x.Serial_Number into g
orderby g.Key
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()
...这将避免“选择新的”
答案 5 :(得分:0)
这可以在LINQ lamda表达式中使用GroupBy和SelectMany来完成
var groupByMax = list.GroupBy(x=>x.item1).SelectMany(y=>y.Where(z=>z.item2 == y.Max(i=>i.item2)));