我试图在richTextBox
中从最高到最低的顺序获得测验的分数。我在名为scoresClass
的班级中保存了球员姓名,测验和得分。在测验结束时,我将课程称为三个richTextBox
,以显示他们的名字,测验和分数。然后我将它们添加到列表中并将列表写入文件。排行榜(richTextBox
)设置为等于文件中的数据。
这是我的代码:
public frmFinal()
{
InitializeComponent();
}
private void frmFinal_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
List<string> scores = new List<string>();
private void frmFinal_Load(object sender, EventArgs e)
{
//sets the leaderboard equal to the file scoreInfo
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
//sets a textbox equal to the players score
rchBxScore.Text = Convert.ToString(scoresClass.score);
rchBxNameScore.Text = scoresClass.name;
rchBxQuizNameScore.Text = scoresClass.quiz;
}
private void btnClearScores_Click(object sender, EventArgs e)
{
//opens the file scoreInfo
FileStream fileStream = File.Open(".\\scoreInfo.bin", FileMode.Open);
//empties the file
fileStream.SetLength(0);
//closes the file
fileStream.Close();
//sets the leaderbaord equal to the file
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
scores.Clear();
}
//creates a bool variable and sets it equal to false
bool saved = false;
private void btnSaveScore_Click(object sender, EventArgs e)
{
//checks if saved equals false
if (saved == false)
{
//if saved equals false, it opens the file scoreInfo
using (StreamWriter scoreInfo = new StreamWriter(".\\scoreInfo.bin", true))
{
scores.Add(scoresClass.name + "\t" + scoresClass.quiz + "\t" + scoresClass.score);
foreach(string score in scores)
{
scoreInfo.WriteLine(score);
}
}
//clears all the players score details
rchBxNameScore.Clear();
rchBxQuizNameScore.Clear();
rchBxScore.Clear();
rchBxScores.Text = File.ReadAllText(".\\scoreInfo.bin");
//sets saved to true
saved = true;
}
}
目前,分数是在输入的时间而非分数。我不确定我将如何订购它们。
这是班级:
public class scoresClass
{
public static int score = 0;
public static string name = "";
public static string quiz = "";
public scoresClass(string userName, int userScore, string userQuiz)
{
name = userName;
score = userScore;
quiz = userQuiz;
}
}
答案 0 :(得分:1)
由于您使用StreamWriter
附加到文件,我会将文件作为scoreClass
的集合重新读取,而不是盲目读取文件并将其转储到richTextBox
}。这些方面的东西。
我也必须改变你的班级定义。
public class scoresClass
{
public int score = 0;
public string name = "";
public string quiz = "";
public scoresClass(string userName, string userQuiz, int userScore)
{
name = userName;
score = userScore;
quiz = userQuiz;
}
}
private List<scoresClass> importScoresFromFile(string path)
{
var listOfScores = new List<scoresClass>();
var rawScores = File.ReadAllLines(path);
foreach (var score in rawScores)
{
string[] info = score.Split('\t');
listOfScores.Add(new scoresClass(info[0], info[1], Convert.ToInt32(info[2])));
}
return listOfScores.OrderByDescending(r => r.score).ToList();
}
一旦你掌握了记忆中的所有分数,你就可以做一点LINQ
工作来对它们进行排序。然后,您可以遍历List<scoresClass>
中的每个值,并根据需要导出到richTextBox
。