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
Sorting in C# In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.
Sort() Method Set -1. List<T>. Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements.
In Python, you can sort a list using the built-in list. sort() method or the built-in sorted() function. The sorted() function creates a new sorted list, while the list. sort() method sorts the list in place.
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.
var sortedList = yourList.OrderBy(x => x.Score);
or use OrderByDescending
to sort in opposite way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With