您如何在LINQ中找到按组的最大值? [英] How do you find the group-wise max in LINQ?
问题描述
我正在尝试解决LINQ中的按组最大"问题.首先,我有一个使用实体框架建模的数据库,其结构如下:
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.
我正在尝试创建一个LINQ查询,该查询允许我在数据库中查找前10名客户订单.简单的案例很容易想到:
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);
但是,我只想在此列表中显示唯一客户.我对LINQ还是有点陌生,但这是我想出的:
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);
这似乎可行,但是我不确定这是否是最佳方法.具体来说,我想知道针对大型数据库进行此类查询的性能.另外,使用组查询中的FirstOrDefault
方法看起来有些奇怪...
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?
推荐答案
您可以这样做:
var q = (
from order in _data.Orders // ObjectQuery<Order>
orderby order.Amount descending select order
).Distinct().Take(10);
我通常会查看生成的SQL,然后看看什么是最好的.
I would normally look at the generated SQL, and see what is the best.
这篇关于您如何在LINQ中找到按组的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!