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

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!