在列表排序中要更改什么以正确排序

1 c# sorting list

我不能完全排序我的名单.它是基于int的排序,我使用CompareTo()形式IComparable,自定义Comparer委托和匿名委托.这对我来说都不起作用.

这是代码:

[TestMethod]
    public void SortingPlayersFirst()
    {
      //arrange
      Player player = new Player("neosb");
      Player player2 = new Player("simone");
      Player player3 = new Player("Alice");
      player.Score = 5;
      player2.Score = 2;
      player3.Score = 10;
      Players players = new Players();
      players.Add(player);
      players.Add(player2);
      players.Add(player3);

      //I have tried this one
      players.Sort(Player.ComparePlayersByScore);
      //and this one
      players.Sort()
      // and this one
      IComparer<Player> comp = Comparer<Player>.Create(
        (p1, p2) => p1.Score.CompareTo(p2.Score));
      players.Sort(comp);

      //this one fails the test
      Assert.AreEqual(player3, players[0], "Highest score is not first");
      //however this one passes the test
      Assert.AreNotEqual(player2, players[2], "Lowest score is not last");
    }

public class Players : List<Player>
  {

  }

public class Player : IComparable<Player>, IEquatable<Player>
  {
    public string Name { get; set; }
    public int Score { get; set; }

    public Player(string name)
    {
      Name = name;
      Score = 0;
    }

    public int CompareTo(Player other)
    {
      return Score.CompareTo(other.Score);
    }

    public static int ComparePlayersByScore(Player player1, Player player2)
    {
      if (player1.Score > player2.Score)
        return 1;
      else if (player1.Score < player2.Score)
        return -1;
      else
        return 0;
    }
  }
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能对这个列表进行排序并通过单元测试以及它为何部分排序.

Jon*_*eet 6

按升序排序,而不是降序...但你的测试要求得分最高的玩家是第一个.这应该工作:

// Use the overload taking a Comparer<Player> delegate for simplicity
players.Sort((p1, p2) => p2.Score.CompareTo(p1.Score));
Run Code Online (Sandbox Code Playgroud)

注意在lambda表达式中使用p1和的反转p2- 这就是你如何反转比较.