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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With