【问题标题】:How to read by streamreader and sort如何通过streamreader读取和排序
【发布时间】:2016-08-12 03:53:40
【问题描述】:

我正在制作一个 passaparola 游戏,在游戏结束时我保存昵称并以流作家作为昵称得分;得分

我正在尝试制作排行榜,但不知道如何在保存时或保存后将它们从高到低排序。

还将它们显示在我写的标签上;

        string[] scoreArray;
        string sc = sr.ReadLine();

        scoreArray = sc.Split(';');
        label2.Text = scoreArray[0];
        label3.Text = scoreArray[1];

在文本文件中写入第一行。无论如何 我怎样才能对它们进行排序并写在标签中?

【问题讨论】:

    标签: c# sorting stream leaderboard reader


    【解决方案1】:

    对数组进行排序,然后使用foreach循环显示结果:

    string[] scoreArray;
    string sc = sr.ReadLine();
    scoreArray = sc.Split(';');
    Array.Sort(scoreArray);
    foreach (string s in scoreArray)
    {
        //Your code here.
    }
    

    【讨论】:

      【解决方案2】:

      LINQ 的OrderBy 扩展方法适合您吗?比如这样:

              string line = "300;100;60;200;100;150";
              string[] scoreArray;
              int[] orderedScoreArray;
      
              scoreArray = line.Split(';');
              orderedScoreArray = (from score in scoreArray
                  orderby Convert.ToInt32(score)
                  select Convert.ToInt32(score)).ToArray();
      
              for (int i = 0; i < orderedScoreArray.Length; i++)
              {
                  Console.WriteLine(orderedScoreArray[i]);
              }
      
              Console.ReadKey();
      

      【讨论】:

        【解决方案3】:

        您无法在从 Stream Reader 中读取时进行排序。您必须在将它们保存到文件之前对值进行排序,或者在将它们全部读取然后对它们进行排序之后再显示它们。

        阅读它们然后排序可能看起来像:

        //define a class to store your scores
        public class Score
        {
            public string Username { get; set; }
            public decimal Score { get; set; }
        
            public Score()
            {
        
            }
        }
        
        //then reading the values
        var scores = new List<Score>();
        string line = "";
        while ((line = sr.ReadLine()) != null)
        {
            var lineArray = line.Split(';');
            scores.Add(new Score{ Username = line[0], Score = line[1] });
        }
        
        // then sort the list using linq
        scores = scores.OrderByDescending(x => x.Score).ToList();
        

        然后你可以浏览分数并显示它们

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-18
          • 2018-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-03
          • 2012-02-23
          • 1970-01-01
          相关资源
          最近更新 更多