rickard rickard - 13 days ago 7
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)
{
listOfSomething.Add(item);
}


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();


Solution:
This code did the trick - thanks!

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

Answer

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()));