如何将含多类型数据的TXT存入数组并按分数降序排序?
问题解答
一、按分数降序排序玩家数据
你当前把每行内容当作字符串排序,自然会按字母顺序排列。要实现按分数降序并保留对应玩家名,需先拆分每行的玩家名和分数,用自定义类封装数据后再排序:
1. 定义玩家数据类
public class Player { public string Name { get; set; } public int Score { get; set; } }
2. 修改读取与排序代码
替换你原有的show_Click方法逻辑:
void show_Click(object sender, EventArgs e) { List<Player> players = new List<Player>(); // 使用using自动释放文件流,避免资源泄漏 using (StreamReader reader = new StreamReader("Leaderboard.txt")) { string line; while ((line = reader.ReadLine()) != null) { ListB1.Items.Add(line); // 拆分每行(支持玩家名带空格的情况,仅拆分为两部分) string[] parts = line.Split(new[] {' '}, 2); // 验证拆分结果并转换分数类型 if (parts.Length == 2 && int.TryParse(parts[1], out int score)) { players.Add(new Player { Name = parts[0], Score = score }); } } } // 按分数降序排序 var sortedPlayers = players.OrderByDescending(p => p.Score).ToList(); // 将排序后的数据添加到ListB2 foreach (var player in sortedPlayers) { ListB2.Items.Add($"{player.Name} {player.Score}"); } }
二、存储不同类型变量到数组
TXT中的混合类型数据无法直接存入单一类型数组,需用自定义类/结构体封装不同类型字段,再通过泛型集合转换为数组:
示例:封装多类型数据
假设TXT每行包含玩家名(字符串)、分数(整数)、游戏时间(日期时间),先定义类:
public class PlayerRecord { public string PlayerName { get; set; } public int Score { get; set; } public DateTime PlayTime { get; set; } }
读取并转换为数组
List<PlayerRecord> records = new List<PlayerRecord>(); using (StreamReader reader = new StreamReader("Leaderboard.txt")) { string line; while ((line = reader.ReadLine()) != null) { // 假设每行格式为:玩家名 分数 yyyy-MM-dd HH:mm:ss string[] parts = line.Split(' '); // 验证并转换各字段类型 if (parts.Length >= 4 && int.TryParse(parts[1], out int score) && DateTime.TryParse($"{parts[2]} {parts[3]}", out DateTime playTime)) { records.Add(new PlayerRecord { PlayerName = parts[0], Score = score, PlayTime = playTime }); } } } // 转换为数组 PlayerRecord[] recordArray = records.ToArray();
三、控制台应用访问Windows Forms
按以下步骤操作:
- 右键控制台项目 → 添加 → 引用 → 勾选
System.Windows.Forms和System.Drawing程序集。 - 在入口方法上添加
[STAThread]属性(WinForms要求单线程单元模式)。 - 编写WinForms调用代码:
using System; using System.Windows.Forms; namespace ConsoleWinFormsDemo { class Program { [STAThread] static void Main(string[] args) { // 创建窗体 Form mainForm = new Form(); mainForm.Text = "控制台调用WinForms"; mainForm.Size = new System.Drawing.Size(350, 250); // 添加按钮控件 Button testBtn = new Button(); testBtn.Text = "点击弹窗"; testBtn.Location = new System.Drawing.Point(100, 80); testBtn.Click += (s, e) => MessageBox.Show("这是控制台里的WinForms弹窗"); mainForm.Controls.Add(testBtn); // 启动WinForms消息循环 Application.Run(mainForm); } } }
内容的提问来源于stack exchange,提问作者Machuchi
相关产品推荐
相关产品推荐

