How to Sort a List<> by a Integer stored in the struct my List<> holds

38,336

Solution 1

I don't know why everyone is proposing LINQ based solutions that would require additional memory (especially since Highscore is a value type) and a call to ToList() if one wants to reuse the result. The simplest solution is to use the built in Sort method of a List

list.Sort((s1, s2) => s1.Score.CompareTo(s2.Score));

This will sort the list in place.

Solution 2

var sortedList = yourList.OrderBy(x => x.Score);

or use OrderByDescending to sort in opposite way

Solution 3

Use LINQ:

myScores.OrderBy(s => s.Score);

Here is a great resource to learn about the different LINQ operators.

Share:
38,336
Lucidity
Author by

Lucidity

Updated on July 09, 2022

Comments

  • Lucidity
    Lucidity almost 2 years

    I need to sort a highscore file for my game I've written.

    Each highscore has a Name, Score and Date variable. I store each one in a List.

    Here is the struct that holds each highscores data.

    struct Highscore
    {
        public string Name;
        public int Score;
        public string Date;
    
        public string DataAsString()
        {
            return Name + "," + Score.ToString() + "," + Date;
        }
    }
    

    So how would I sort a List of type Highscores by the score variable of each object in the list?

    Any help is appreciated :D

  • Jeff Mercado
    Jeff Mercado almost 13 years
    The result of calling OrderBy() is not a list however.
  • Xonatron
    Xonatron over 3 years
    This works, but can you break down what is happening to make it work?
  • Stilgar
    Stilgar over 3 years
    The method Sort takes a delegate argument for comparing two elements from the array which it uses to perform sorting. The lambda passed as an argument uses the default CompareTo method of the Score property. By convention comparing returns -1, 0, 1 depending on how elements relate to each other.