【问题标题】:Read from a text file and order the rows (each row int + String)从文本文件中读取并排序行(每行 int + String)
【发布时间】:2020-10-15 00:39:36
【问题描述】:

我正在为类似于 Subway Surfers 的大学项目编写游戏。我的一切工作正常,但我的问题出在我编写的书签选项中。

当您在游戏中输了时,您必须输入一个名称,该名称会以<int score> <string name> 格式写入并保存在一个文本文件中,例如:

11245 Lucas
10123 Marco
 2394 Ricky

然后在游戏的菜单中,您可以选择书签,然后读取文本文件并在屏幕上显示一个分数,另一个分数是在每个游戏中写入的名称。

现在我的问题是我希望对书签进行排序,最高的在顶部,但我不知道该怎么做,因为我在每一行都有一个 int 和一个字符串,它们是相关的,因此我可以'没有一个分数文件和一个名称文件,因此当我订购分数时,我丢失了有关谁获得每个分数的信息。

我能做些什么来解决这个问题?

编辑: 我正在添加与我的问题相关的代码部分。 这是显示书签的方法

static void ReadBookmark()
        {
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("BOOKMARKS");
            string myfile = @"bookmarks.txt";
            if (File.Exists(myfile) == false)
            {
                Console.WriteLine("\n");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("NO BOOKMARKS. PLAY SOME GAMES!");
                Console.Write("\nPRESS A KEY TO RETURN...");
                Console.ReadKey();
            }
            else
            {
                Console.WriteLine("\n");
                Console.ForegroundColor = ConsoleColor.Green;
                using (StreamReader sr = File.OpenText(myfile))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine($"\t{s}");
                    }
                }
                Console.ForegroundColor = ConsoleColor.White;
                Console.Write("\n\nPRESS A KEY TO RETURN...");
                Console.ReadKey();
            }
        }

这是在文件中写入名称和分数的代码。

public void SaveBookmark(int score, string name)
        {
            string myfile = @"bookmarks.txt";
            using (StreamWriter sw = File.AppendText(myfile))
            {
                sw.WriteLine($"{score} {name}");
            }
        }

【问题讨论】:

  • 显示你当前的代码
  • 我刚刚添加了它

标签: c# file archive bookmarks


【解决方案1】:

您可以在空白处分割每一行,然后使用int.Parse 获取第一部分的数值,然后使用OrderByDescending 使用该值:

var orderedLines = File.ReadLines(myfile)
    .OrderByDescending(line => int.Parse(line.Split()[0]))
    .ToList();

【讨论】:

    【解决方案2】:

    在发布代码之前完成的安全操作的完整示例。 这将允许名称中有空格。

    public List<ScoreItem> GetScores()
    {
        var scoreList = new List<ScoreItem>();
        using (var fs = File.OpenRead("myPath"))
        using (var sr = new StreamReader(fs))
        {
            while (!sr.EndOfStream)
            {
                var line = sr.ReadLine();
                if (string.IsNullOrWhiteSpace(line)) continue;
    
                var scoreMatch = Regex.Match(line, @"\A\d*");
                if (!scoreMatch.Success)
                    throw new Exception($"Failed to parse score from line [{line}].");
    
                var nameMatch = Regex.Match(line, @"(?<!\A\d*).*\Z");
                if (!nameMatch.Success)
                    throw new Exception($"Failed to parse name from line [{line}].");
    
                if (!int.TryParse(scoreMatch.Value, out var score))
                    throw new Exception($"Failed to cast score to a number from line [{line}].");
    
                scoreList.Add(new ScoreItem {Name = nameMatch.Value, Score = score});
            }
    
            return scoreList.OrderByDescending(s => s.Score).ToList();
        }
    }
    
    public class ScoreItem
    {
        public string Name { get; set; }
        public int Score { get; set; }
    }
    

    【讨论】:

    • 非常有用,我要试试。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多