- Home /
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.
Answer by Bunny83 · Mar 30, 2014 at 10:14 PM
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));
Thank you for your reply! Is there a more conventional way when there are more than 2 players? Because my game probably supports up to 8...I also have another question. I am using
public List<Player> PlayerList = new List<Player> ();
Would this be compatible with this method?
Uhm, that works for any number of players. The delegate is just the comparison function. The Sort method sorts the whole list based on the compare function.
Okay thanks xD I am going to have to check the reference etc. to understand this a bit better
The Sort method takes an optional delegate which is used as compare method. The return value tells the sorting algorithm is p1 is greater than p2, equal or smaller. It returns a value:
greater than 0 if p1 is greater than p2
of 0 if p1 equals p2
smaller than 0 if p1 is smaller than p2
Depending on the sort algorithm the Sort method calls the delegate repeatedly for various pairs to get the elements sorted. Depending on the element count Sort might use the Heapsort, QuickSort or other algorithms.
Answer by jbvobling · Aug 03, 2021 at 04:32 AM
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.