stormist
stormist

Reputation: 5905

Sorting a list by a double within the class

I have a list, winningCombos, of type class winningCombo, which has a class of type spin. Like so:

 public List<winningCombo> winningCombos;

  public class winningCombo
    {
        public List<spin> winningSymbols; 
        public double cumulativeValue;
    }


  public class spin
    {
        public string Name;
        public double Value;
    }

What is an efficient way to sort the list winningCombos in order by the value of the double cumaltiveValue within each class winningCombo? Some of these have the same value. So winningCombos[0] should be the smallest value of the double cumaltiveValue and work its way up. Thanks for any ideas!

Upvotes: 0

Views: 1077

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

This can be sorted in place via List<T>.Sort like so:

winningCombos.Sort( (l, r) => l.cumulativeValue.CompareTo(r.cumulativeValue));

You could also use LINQ to get back sorted results:

var sorted = winningCombos.OrderBy(wc => wc.cumulativeValue);

(Note the latter doesn't change the original collection, but returns a new, sorted IEnumerable<winningCombo>.)

Upvotes: 4

Related Questions