simone
simone

Reputation: 13

What to change in list sorting to sort it properly

I can't sort my list entirely. It's int based sorting and I used CompareTo() form IComparable, custom Comparer delegate, and anonymous delegate. None of this work for me.

here is the code:

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

what do I have to do to sort this list and pass the unit test and why it's partly sorted.

Upvotes: 1

Views: 92

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504032

You're sorting it in ascending order, rather than descending... but your test requires that the highest scoring player is first. This should work:

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

Note the reversal of the use of p1 and p2 in the lambda expression - that's how you reverse the comparison.

Upvotes: 6

Related Questions