Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort a list by an element inside the object the list uses?

Tags:

c#

list

sorting

I am working on a piece of coursework and part of this involves me having to have a working scoreboard in my game, however, I need a way to sort my list of the Score object by score.score. As my Score object contains the players name and also the level they reached.

I am not very experienced in programming and have been doing it for less than a year, all I've found from searching is people talking about lambda or IComparable, both of which I don't know anything about or how to use and MSDN doesn't seem to make it easy to understand for me :(

I'm pulling my hair out here, any help would be great!

In pseudo all I need is:

List<Score> scores;
// Load in scores
scores.Sort(//sort by score.actualScore)

So that I can add to and remove from the list in the correct places when a new score is added.

like image 534
Stephen Foster Avatar asked Dec 21 '25 11:12

Stephen Foster


2 Answers

var ordered = scores.OrderBy(x => x.ActualScore).ToList();

Or:

var ordered = scores.OrderByDescending(x => x.ActualScore).ToList();
like image 151
Alex Avatar answered Dec 24 '25 00:12

Alex


The simplest way would be to pass it a Comparison delegate. For your example, that would be:

scores.Sort((a, b) => a.actualScore - b.actualScore);
like image 36
Ry- Avatar answered Dec 24 '25 00:12

Ry-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!