简体   繁体   English

Max的Linq分组不起作用

[英]Linq grouping by Max not working

I have a table with products 我有一张产品表

Id  |  Name      |  Order
1   | product 1  |    5
1   | product 1  |    9
1   | product 1  |    2 
2   | product 2  |    0
3   | product 3  |    1

I need to return just the product with the max order number: 我只需要退回具有最大订购号的产品:

Id  |  Name      |  Order

1   | product 1  |    9
2   | product 2  |    0 
3   | product 3  |    1

tried this but it's not working: 试过这个,但它不起作用:

var items = (from i in db.products
                 group i by new
                 {
                     i.Id,
                     i.Name,
                     i.Order
                 } into g

                 select new
                 {
                     g.Key.Id,
                     g.Key.Name,
                     Order = g.Where(d => d.Order == g.Max(xx => xx.Order )).First().Order     })

but it stills return all the 5 results. 但它仍然会返回所有5个结果。 thank you 谢谢

Change 更改

             group i by new
             {
                 i.Id,
                 i.Name,
                 i.Order
             } into g

into

             group i by new
             {
                 i.Id,
                 i.Name,
             } into g

I think I would also rewrite the the last expression to 我想我也会重写最后一个表达式

Order = g.OrderByDescending(xx => xx.Order).First().Order

Mostly because I think it is easier to read, but the generated SQL might be more efficient too. 主要是因为我认为它更容易阅读,但生成的SQL也可能更有效。 But this is just a matter of taste and any performance difference can be verified with SQL Profiler. 但这只是一个问题,可以使用SQL Profiler验证任何性能差异。

The reason you still have 5 rows is because Order is different for your group by combination. 您仍有5行的原因是因为组合的顺序与您的组不同。 This would be the query if you wanna use the original one, or use the order by to get the max Order. 如果您想使用原始订单,或使用order by来获取最大Order,这将是查询。

var items = (from i in db.products
                 group i by new
                 {
                     i.Id,
                     i.Name                     
                 } into g

                 select new
                 {
                     g.Key.Id,
                     g.Key.Name,
                     Order = g.Where(d => d.Order == g.Max(xx => xx.Order )).First().Order     })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM