[英]how to order the data being written to a text file by score in c#
我正在为我的计算机课程做一个测验应用程序,并且在最终屏幕上工作,在最终屏幕上,我有一个名为savescore()的方法
savescore()旨在将用户的用户名,分数和时间保存到文本文件中。 savescore()方法可以将用户详细信息完美地保存到一个名为scores的文本文件中,但是我的问题是,当我将用户详细信息写入文本文件时,我希望数据按照分数降序排列并写入到scores文本文件中。我不知道该怎么做。
private void SaveScore()
{
string file = @"..\..\textfiles\scores.txt";
try
{
//
// Create file if not exists
//
if (!File.Exists(file))
{
File.Create(file).Dispose();
}
//
// Create DataTable
//
DataColumn nameColumn = new DataColumn("name", typeof(String));
DataColumn scoreColumn = new DataColumn("score", typeof(int));
DataColumn timeColumn = new DataColumn("time", typeof(long));
DataTable scores = new DataTable();
scores.Columns.Add(nameColumn);
scores.Columns.Add(scoreColumn);
scores.Columns.Add(timeColumn);
//
// Read CSV and populate DataTable
//
using (StreamReader streamReader = new StreamReader(file))
{
streamReader.ReadLine();
while (!streamReader.EndOfStream)
{
String[] row = streamReader.ReadLine().Split(',');
scores.Rows.Add(row);
}
}
Boolean scoreFound = false;
//
// If user exists and new score is higher, update
//
foreach (DataRow score in scores.Rows)
{
if ((String)score["name"] == player.Name)
{
if ((int)score["score"] < player.Score)
{
score["score"] = player.Score;
score["time"] = elapsedtime;
}
scoreFound = true;
break;
}
}
//
// If user doesn't exist then add user/score
//
if (!scoreFound)
{
scores.Rows.Add(player.Name, player.Score, elapsedtime);
}
//
// Write changes to CSV (empty then rewrite)
//
File.WriteAllText(file, string.Empty);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("name,score,time");
foreach (DataRow score in scores.Rows)
{
stringBuilder.AppendLine(score["name"] + "," + score["score"] + "," + score["time"]);
}
File.WriteAllText(file, stringBuilder.ToString());
}
catch (Exception ex)
{
MessageBox.Show("Error saving high score:\n\n" + ex.ToString(), "Error");
}
}
因此,我可以编辑我当前的代码,以按照分数的降序顺序保存用户详细信息,这是非常棒的,在此先感谢。
您可以使用DataTable.Select方法来实现。 使用select方法,可以对表中的行进行过滤和排序。 这是使用该方法对数据进行排序的已更改的foreach
语句。
foreach (DataRow score in scores.Select(null, "score DESC"))
{
stringBuilder.AppendLine(score["name"] + "," + score["score"] + "," + score["time"]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.