可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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
回答1:
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.
回答2:
var sortedList = yourList.OrderBy(x => x.Score);
or use OrderByDescending
to sort in opposite way
回答3:
Use LINQ:
myScores.OrderBy(s => s.Score);
Here is a great resource to learn about the different LINQ operators.
回答4:
List<Highscore> mylist = GetHighScores(); var sorted = mylist.OrderBy(h=>h.Score);
回答5:
This will sort the list with the highest scores first:
IEnumerable<Highscore> scores = GetSomeScores().OrderByDescending(hs => hs.Score);