How do you find the group-wise max in LINQ?

一世执手 提交于 2019-12-12 04:38:09

问题


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?


回答1:


You could do:

var q = (
    from order in _data.Orders  // ObjectQuery<Order>
    orderby order.Amount descending select order
).Distinct().Take(10);

I would normally look at the generated SQL, and see what is the best.




回答2:


Customer
.Select(c=>new {Order= c.Orders.OrderByDescending(o=>o.Total).First()})
.OrderByDescending(o=>o.Total)
.Take(10);


来源:https://stackoverflow.com/questions/2034800/how-do-you-find-the-group-wise-max-in-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!