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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/157786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:12:09  来源:igfitidea点击:

How do I get the MAX row with a GROUP BY in LINQ query?

.netlinqlinq-to-sql

提问by SpoiledTechie.com

I am looking for a way in LINQ to match the follow SQL Query.

我正在 LINQ 中寻找一种方法来匹配以下 SQL 查询。

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

Really looking for some help on this one. The above query gets the max uid of each Serial Number because of the Group BySyntax.

真的在寻找一些帮助。由于Group By语法的原因,上述查询获取每个序列号的最大 uid 。

采纳答案by tvanfosson

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

回答by DamienG

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

回答by Lu55

In methods chain form:

在方法链形式中:

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

回答by denis_n

I've checked DamienG's answer in LinqPad. Instead of

我在 LinqPad 中检查了 DamienG 的回答。代替

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

should be

应该

g.Max(s => s.uid)

Thank you!

谢谢!

回答by Javier

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

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

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

... this will avoid the "select new"

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