Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Sum Nested collection with GroupBy and OrderByDescending

Tags:

c#

linq

group-by

I have:

public class Order
{
    public string Customer;
    public List<OrderLine> OrderLines;
}

public class OrderLine
{
    public decimal Quantity;
    public decimal UnitPrice;
}

My goal is to search the list of customer order by descending amount. (Amount == Addition of every orderLine of Quantity*UnitPrice)

Let's say we have 6 orders of 2 customers (Customer1, Customer2). Each customer has 3 orderLines.

I'm trying with:

var result = Database.GetAllOrders().OrderByDescending(order =>  
          order.Lines.Sum(ol=>ol.Quantity*ol.UnitPrice))
         .GroupBy(order=>order.CustomerName, 
         order=>order.Lines.Sum(ol=>ol.Quantity*ol.UnitPrice),
            (customerName, amount) => new {Customer=customerName, Amount=amount});

but I obtain something like this:

Customer2:
- Amount: 78
- Amount: 89
- Amount: 12

Customer1:
- Amount: 64
- Amount: 36
- Amount: 28

while I'm trying to seek is:

Customer2:
- Amount 179

Customer1:
- Amount 128

Any suggestion, please?
Thanks so much!

like image 259
Demons Avatar asked Aug 21 '12 05:08

Demons


1 Answers

It sounds like you need to be doing the grouping and summing before the ordering, and only group by customer name (or ideally, customer ID):

var query = Database.GetAllOrders()
                    .GroupBy(order => order.CustomerName)
                    .Select(orders => new { 
                        Customer = orders.Key,
                        Amount = orders.Sum(o => o.OrderLines.Sum(
                                                 l => l.Quantity * l.UnitPrice))
                    })
                    .OrderByDescending(x => x.Amount);
like image 149
Jon Skeet Avatar answered Nov 06 '22 02:11

Jon Skeet