1

我无法对我的列表进行完全排序。它是基于 int 的排序,我使用了 CompareTo() 形式的 IComparable、自定义比较器委托和匿名委托。这些都不适合我。

这是代码:

[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;
    }
  }

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

4

1 回答 1

6

按升序而不是降序对其进行排序……但是您的测试要求得分最高的玩家排在第一位。这应该有效:

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

注意在 lambda 表达式中使用p1and的反转p2——这就是你反转比较的方式。

于 2013-09-26T07:45:44.873 回答