rickard rickard - 1 year ago 90
C# Question

Sum and order nested List<double>

I want to Sum() a List of accumulated doubles values - the list is inside another List.

This is the Object that has my List of accumulated double values

public class Something
public int Id {get; set;}
public string Company {get; set;}
public List<double> AccumulatedResults { get; set; }

The class "something" is then added to another list.

var listOfSomething = new List<Something>();

foreach(var item in anotherList)

Now i want to order listOfSomething by the list called AccumulatedResults. I have come up with this - but it's not working obviously

var topResults = listOfSomething.GroupBy(g => g.Id).SelectMany(s => s.OrderByDescending(d => d.Result.Sum())).Take(10).ToList();

This code did the trick - thanks!

var topResults = listOfResults.OrderByDescending(s => s.AccumulatedResults.Sum());

Answer Source

You can order your the objects of Something in the list just by the sum up their AccumulatedResults as value to order by:

listOfSomething.OrderBy(S => S.AccumulatedResults.Sum()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download