如何按存储在结构列表中的整数对列表进行排序

时间:2022-01-07 00:35:41

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.

每个高分都有一个名称,分数和日期变量。我将每个存储在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

任何帮助表示赞赏:D

5 个解决方案

#1


49  

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

我不知道为什么每个人都在提出需要额外内存的基于LINQ的解决方案(特别是因为Highscore是一种值类型),如果想要重用结果,则调用ToList()。最简单的解决方案是使用List的内置Sort方法

list.Sort((s1, s2) => s1.Score.CompareTo(s2.Score));

This will sort the list in place.

这将对列表进行排序。

#2


5  

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

or use OrderByDescending to sort in opposite way

或使用OrderByDescending以相反的方式排序

#3


1  

Use LINQ:

使用LINQ:

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

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

这是了解不同LINQ运算符的绝佳资源。

#4


0  

List<Highscore> mylist = GetHighScores();

var sorted = mylist.OrderBy(h=>h.Score);

#5


0  

This will sort the list with the highest scores first:

这将首先对列表进行排序:

IEnumerable<Highscore> scores = GetSomeScores().OrderByDescending(hs => hs.Score);

#1


49  

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

我不知道为什么每个人都在提出需要额外内存的基于LINQ的解决方案(特别是因为Highscore是一种值类型),如果想要重用结果,则调用ToList()。最简单的解决方案是使用List的内置Sort方法

list.Sort((s1, s2) => s1.Score.CompareTo(s2.Score));

This will sort the list in place.

这将对列表进行排序。

#2


5  

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

or use OrderByDescending to sort in opposite way

或使用OrderByDescending以相反的方式排序

#3


1  

Use LINQ:

使用LINQ:

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

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

这是了解不同LINQ运算符的绝佳资源。

#4


0  

List<Highscore> mylist = GetHighScores();

var sorted = mylist.OrderBy(h=>h.Score);

#5


0  

This will sort the list with the highest scores first:

这将首先对列表进行排序:

IEnumerable<Highscore> scores = GetSomeScores().OrderByDescending(hs => hs.Score);