Paul Paul - 3 months ago 12
C# Question

C# Lambda OrderByDescending and Sum

I'm wanting to sort an list of values by descending order of total sum of quantity without overwriting the original value of the quantity.

So, let assume my list of data is:

Reason=Quality, Quantity=10
Reason=Quality, Quantity=10
Reason=Customer, Quantity=8
Reason=Carrier, Quantity=17
Reason=Customer, Quantity=1


How would I perform an lambda expression to order these by total amount? I'm hoping to get the following:

Reason=Quality, Quantity=10
Reason=Quality, Quantity=10
Reason=Carrier, Quantity=17
Reason=Customer, Quantity=8
Reason=Customer, Quantity=1


Quality is first because total value is 20.
Customer is last because total value is 1.

This is what I've got at the moment but there isn't anyway to SUM up the data without modifying the original data

eData.OrderByDescending(o => o.Quantity);


The only way I can think to do this task is to add another variable and do Select with Sum to add it all up new variable then OrderByDescending on that value. However, just want to see if there is an easier way before I do that.

Answer

You can group the items by Reason, and then order the groups by the sum of Quantity within each group, and then flatten the groups into individual items using SelectMany.

var result =
    eData
        .GroupBy(x => x.Reason)
        .OrderByDescending(g => g.Sum(x => x.Quantity))
        .SelectMany(g => g)
        .ToList();