亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 C# 中按分數對寫入文本文件的數據進行排序

如何在 C# 中按分數對寫入文本文件的數據進行排序

C#
偶然的你 2022-11-21 15:44:26
我正在為我的計算課程做一個測驗應用程序,我正在結束屏幕上工作,在結束屏幕上我有一個名為 savescore() 的方法savescore() 用于將用戶的用戶名、分數和時間保存到文本文件中。savescore() 方法完美地將用戶詳細信息保存到名為 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;                }            }所以我有人可以編輯我當前的代碼,以根據分數的降序保存用戶詳細信息,這將是非常棒的,在此先感謝。
查看完整描述

1 回答

?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

您可以使用DataTable.Select 方法來實現。使用 select 方法,您可以過濾和排序表中的行。下面是foreach使用該方法對數據進行排序的已更改語句。


foreach (DataRow score in scores.Select(null, "score DESC"))

{

   stringBuilder.AppendLine(score["name"] + "," + score["score"] + "," + score["time"]);

}


查看完整回答
反對 回復 2022-11-21
  • 1 回答
  • 0 關注
  • 78 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號