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

前端 未结 5 1137
死守一世寂寞
死守一世寂寞 2021-02-04 02:11

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 tha

相关标签:
5条回答
  • 2021-02-04 02:36

    This will sort the list with the highest scores first:

    IEnumerable<Highscore> scores = GetSomeScores().OrderByDescending(hs => hs.Score);
    
    0 讨论(0)
  • 2021-02-04 02:44
    var sortedList = yourList.OrderBy(x => x.Score);
    

    or use OrderByDescending to sort in opposite way

    0 讨论(0)
  • 2021-02-04 02:53

    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.

    0 讨论(0)
  • 2021-02-04 02:55
    List<Highscore> mylist = GetHighScores();
    
    var sorted = mylist.OrderBy(h=>h.Score);
    
    0 讨论(0)
  • 2021-02-04 02:58

    Use LINQ:

    myScores.OrderBy(s => s.Score);
    

    Here is a great resource to learn about the different LINQ operators.

    0 讨论(0)
提交回复
热议问题