如何在 LINQ 中找到分组最大值?
我正在尝试解决 LINQ 中的“group-wise max”问题。首先,我有一个使用实体框架建模的数据库,其结构如下:
Customer:
---------
CustomerID : Int32
Name : String
Order:
-------
OrderID : Int32
CustomerID : Int32
Total : Decimal
这使我能够从客户导航到她的订单,并从订单导航到所有者。
我正在尝试创建一个 LINQ 查询,该查询允许我在数据库中查找前 10 个客户订单。这个简单的案例很容易想到:
var q = (
from order in _data.Orders // ObjectQuery<Order>
orderby order.Amount descending select order
).Take(10);
但是,我只想在此列表中显示唯一的客户。我对 LINQ 还是有点陌生,但这就是我的想法:
var q = (
from order in _data.Orders // ObjectQuery<Order>
group order by order.Customer into o
select new {
Name = o.Key.Name,
Amount = o.FirstOrDefault().Amount
}
).OrderByDescending(o => o.Amount).Take(10);
这似乎有效,但我不确定这是否是最好的方法。具体来说,我想知道针对非常大的数据库进行此类查询的性能。另外,使用组查询中的 FirstOrDefault 方法看起来有点奇怪......
任何人都可以提供更好的方法,或者保证这是正确的方法吗?
I'm trying to solve the "group-wise max" problem in LINQ. To start, I have a database modeled using the Entity Framework with the following structure:
Customer:
---------
CustomerID : Int32
Name : String
Order:
-------
OrderID : Int32
CustomerID : Int32
Total : Decimal
This gives me navigation from a Customer to her orders and an Order to the owner.
I'm trying to create a LINQ query that allows me to find the top-10 customer orders in the database. The simple case was pretty easy to come up with:
var q = (
from order in _data.Orders // ObjectQuery<Order>
orderby order.Amount descending select order
).Take(10);
However, I'd like to only show unique customers in this list. I'm still a bit new to LINQ, but this is what I've come up with:
var q = (
from order in _data.Orders // ObjectQuery<Order>
group order by order.Customer into o
select new {
Name = o.Key.Name,
Amount = o.FirstOrDefault().Amount
}
).OrderByDescending(o => o.Amount).Take(10);
This seems to work, but I'm not sure if this is the best approach. Specifically, I wonder about the performance of such a query against a very large database. Also, using the FirstOrDefault
method from the group query looks a little strange...
Can anyone provide a better approach, or some assurance that this is the right one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
我通常会查看生成的 SQL,看看什么是最好的。
You could do:
I would normally look at the generated SQL, and see what is the best.