Sorting a List by Variable?

Hey! I am trying to sort a list of players for my networked game by “score”. This is a variable in the player class. Can someone tell me how I could do this? I want the player with the highest score to be nr 1 and so on.

Just write a compare method like this:

    // C#
    static int SortByScore(PlayerClass p1, PlayerClass p2)
    {
        return p1.score.CompareTo(p2.score);
    }

And then sort your List like this:

    playerList.Sort(SortByScore);

If you want you can of course use a lambda-expression like this:

    playerList.Sort((p1,p2)=>p1.score.CompareTo(p2.score));

Hello @Bunny83
I know it’s been 4 years, but I have a small and fast question for you

I’ve used what you said:

playerList.Sort((p1,p2)=>p1.score.CompareTo(p2.score));

That returns the list ordered by ascending (1,2,3,4). My question is how could I sort it by descending(4,3,2,1)
Thanks in advance @Bunny83 :smiley:

I encountered some data that is not sorted (I have more than 250 object data) when using name for sorting in an Object Data.

playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name));

To solve this, I tried to process this 5x
playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name)); playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name)); playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name)); playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name)); playerList.Sort((p1,p2)=>p1.name.CompareTo(p2.name));
and the sort result was success. in ascending order.

Just add another same process if there are still some unsorted data if using more data.