C#对类对象列表进行排序

时间:2015-02-19 19:22:50

标签: c#

我试图按照“得分”的降序对列表进行排序。变量。我该怎么做? 这是我用来设置列表的代码:

          private void LeaderboardScreen_Load(object sender, EventArgs e)
  {
      //GETTING VARIABLES FOR THE CLASS OBJECT
      using (var fileStream = File.OpenRead(".\\InputInfo.bin"))
      using (var streamReader = new StreamReader(fileStream, true))
      {
          string line;
          while ((line = streamReader.ReadLine()) != null) ;
      }
      var lines = File.ReadLines(".\\InputInfo.bin");
      foreach (var line in lines)
      {
          string[] words = line.Split(); //Splits the line into seperate words, and puts them into an array called 'words'
          string name = words[0]; // Makes the first word the name
          string age = words[1]; //Makes the second word the age
          string gender = words[2];//Makes the third word the gender
          int score = Convert.ToInt32(words[3]);//Makes the forth word the score

          //SETTING UP THE LIST
          List<Player> players = new List<Player>(); 
          players.Add(new Player(name, age, gender, score));
      }
  }

谢谢!

3 个答案:

答案 0 :(得分:3)

using System.Linq;

players = players.OrderByDescending(i => i.Score).ToList();

因为你似乎是linq的一个新手,所以这是一个优化的版本&#34;

lines.Select(line => 
  {
      string[] words = line.Split(); //Splits the line into seperate words, and puts them into an array called 'words'
      string name = words[0]; // Makes the first word the name
      string age = words[1]; //Makes the second word the age
      string gender = words[2];//Makes the third word the gender
      int score = Convert.ToInt32(words[3]);//Makes the forth word the score
      return new Player(name, age, gender, score);
  }).OrderByDescending(i => i.Score).ToList();

它避免了两个列表实例化,以及整个集合上的两个循环。

答案 1 :(得分:1)

您只需使用OrderBy声明:

players = players.OrderBy(x => -x.Score).ToList();

通过使用减号(-) - 我假设得分是一个数值 - 你颠倒顺序。

但是,您在new List<Player>();循环中每次构建foreach时都会出现错误,因此列表不会存储以前的项目。您应该在进入List<Player>循环之前构建foreach ,并在<{strong> foreach循环之后对其进行排序

答案 2 :(得分:0)

虽然Linq在语法上有光泽,但它有点浪费。最终的.ToList()正在创建列表的副本。 许多非Linq解决方案之一是将自定义比较函数传递给Sort(...)

    public void DoStuff()
    {
        List<Player> players = new List<Player>();
        foreach (var line in lines)
        {
            // Fill your players list
        }

        players.Sort(ComparePlayersDescending);
    }

    public int ComparePlayersDescending(Player p1, Player p2)
    {
        int scoreDiff = p2.Score - p1.Score;
        if (scoreDiff != 0)
            return scoreDiff;
        else
            return p2.Name.CompareTo(p1.Name);
    }

为了我自己的好奇心,我运行了Linq方法和这个较旧的方法,并测量了在50,000个简单播放器对象列表中分配的内存。您既可以提高效率,也可以使用小代码,但不能同时使用:)

  • players.Sort()分配了8,192个字节。
  • players.OrderByDescending分配了1,857,296字节。

        GC.Collect();
        long memCur = GC.GetTotalMemory(false);
        //players = players.OrderByDescending(i => i.Score).ToList();
        players.Sort(ComparePlayersDescending);
        long memNow = GC.GetTotalMemory(false);
        MessageBox.Show(string.Format("Total Memory: {0} {1}, diff {2}", memCur, memNow, memNow - memCur));