C# 按分数对行进行排序
本文关键字:排序 | 更新日期: 2023-09-27 18:34:44
我有一个名为Player的类,它具有属性名称和分数,并且在每场比赛之后,它们都使用方法File.AppendAllText(path, content+Environment.NewLine);
写入文件中。现在,当单击标签"分数"并加载新表单时,我必须将它们添加到listBox中。但我想使用我的类播放器,并将项目添加到列表中或作为播放器的东西,而不仅仅是从文件中加载它们......我使用了如下所示的SortedList
...
SortedList<int, Player> topList = new SortedList<int, Player>();
private void Scores_Load(object sender, EventArgs e)
{
topList.Clear();
string filename = "highscores.txt";
using (StreamReader sr = File.OpenText(filename))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] s = line.Split(';');
string name = s[0];
int score = int.Parse(s[1]);
Player newPlayer = new Player(name, score);
if (!topList.ContainsKey(score))
topList.Add(score, newPlayer);
}
}
Output();
}
private void Output()
{
lstScores.Items.Clear();
int rank = 1;
foreach (int k in topList.Keys.Reverse())
{
if (rank < 10)//top 9
{
Player temp = (Player)topList[k];
lstScores.Items.Add(" " + rank.ToString() + "'t" + temp.ToString());//override of method ToString(), so it returns in format Name+"'t"+Score;
}
rank++;
}
}
现在这是可以接受的,但这里的问题是我不能有两个相同的键,在这种情况下,键是分数......所以我想知道如何修改它,以便我可以有两个或多个相同的分数?....也许我应该使用 List<>
,但我不知道如何按分数对该列表进行排序,因为我在同一行文件中有字符串 + int(名称 + 分数(?
您可以使用 List:
List<Player> players = new List<Player>();
players.Add(new Player(name, score));
并按分数排序:
var sorted = players.OrderByDescending(p => p.Score).ToList();
读取文件并生成播放器,然后使用 Link OrderBy 运算符:
private IEnumerable<Player> ReadPlayers(TextReader rd){
string line;
while ((line = sr.ReadLine()) != null)
{
string[] s = line.Split(';');
string name = s[0];
int score = int.Parse(s[1]);
yield return new Player(name, score);
}
}
private void Scores_Load(object sender, EventArgs e)
{
string filename = "highscores.txt";
using (StreamReader sr = File.OpenText(filename)){
var sortedPlayers= ReadPlayers(rd)
.OrderByDescending(x=x.Score)
.Take(10)
.Select((p,r)=>$"rank {r+1}:{p.Name} : {p.Score}");
lstScore.Items.Clear();
foreach(var p in sortedPlayers) lstScore.Items.Add(p);
}
使用 List 而不是 SortedList,并使用 OrderBy Linq 方法 (System.Linq(:
public class Player
{
public string Name { get; set; }
public int Score { get; set; }
}
var topList = new List<Player>();
topList = topList.OrderBy(x => x.Score);