gpt4 book ai didi

c# - 在列表排序中更改什么以正确排序

转载 作者:太空宇宙 更新时间:2023-11-03 19:13:10 24 4
gpt4 key购买 nike

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

代码如下:

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

我需要做什么才能对这个列表进行排序并通过单元测试,以及为什么它是部分排序的。

最佳答案

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

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

请注意在 lambda 表达式中反转使用 p1p2 - 这就是反转比较的方式。

关于c# - 在列表排序中更改什么以正确排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com