我如何获得MAX排在LINQ查询GROUP BY?(How do I get the MAX row

2019-08-19 03:58发布

我要寻找一个在LINQ的方式,以配合后续的SQL查询。

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

真的找上这一个一定的帮助。 上述查询得到,因为每个序列号的最大UID Group By语法。

Answer 1:

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


Answer 2:

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


Answer 3:

我检查DamienG在LinqPad答案。 代替

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

应该

g.Max(s => s.uid)

谢谢!



Answer 4:

在方法链形式:

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


Answer 5:

答案是确定的,如果你只需要这两个领域,但对于更复杂的对象,也许这种方法可能是有用的:

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

...这将避免“选择新的”



文章来源: How do I get the MAX row with a GROUP BY in LINQ query?