Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 823
Lucidity Avatar asked Jun 21 '11 11:06

Lucidity


People also ask

Can you sort a list in C#?

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.

How do you sort a class list in C#?

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.

How do I sort a list of numbers in Python?

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.


2 Answers

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.

like image 145
Stilgar Avatar answered Sep 24 '22 07:09

Stilgar


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

or use OrderByDescending to sort in opposite way

like image 22
Stecya Avatar answered Sep 24 '22 07:09

Stecya