我的课程Player
包含字段name
和points
。即。
class Player { string name, int points }.
我有一组这些对象:
Program.playerList = new ArrayList();
我在Windows窗体程序中显示这些对象。我想根据玩家类的数量点(最高点数)按顺序显示它们。我该怎么做?
答案 0 :(得分:2)
你有ArrayList
。
首先,想想你是否真的需要它
您将在那里存储Player
个对象,因此,如果它是强类型数组Player[]
或List<Player>
会更好。
但是,如果由于某些原因需要ArrayList
,则需要实施IComparer
。
public class PlayersByPointsComparer : IComparer
{
private readonly IComparer _baseComparer;
public int Compare(object x, object y)
{
return ((Player)x).Points - ((Player)y).Points;
}
}
// ...
Program.playerList.Sort(new PlayersByPointsComparer());
但是,它会有非Player
类型的对象,它会抛出异常。如果不 - 那么您需要ArrayList
吗?
如果您使用Array
替换,则可以使用Array.Sort
或LINQ OrderBy
方法。
Array.Sort(Program.playerList, (a, b) => (a.points - b.points));
// or
Program.playerList = Program.playerList.OrderBy(x => x.Points).ToArray();
如果您有List
,那就是如何排序。
Program.playerList.Sort(new PlayersByPointsComparer());
// or
Program.playerList.Sort((a, b) => (a.Points - b.Points));
// or
Program.OrderBy(a => a.Points).ToList();
答案 1 :(得分:2)
请使用通用集合Type<Player>
,与ArrayList
相比,它有一些优势。一个是数组项的类型检查,第二个是使用Linq
的可能性。
您可以使用
Program.playerList = Program.playerList.OrderBy(p => p.points).ToList()
或(没有Linq)
Program.playerList.Sort((a, b) => a.points.CompareTo(b.points));
答案 2 :(得分:2)
这可以是你的玩家类:
class Player : IComparable<Player>
{
public string Name { get; set; }
public int Points { get; set; }
public int CompareTo(Player other)
{
// Alphabetic sort if points are equal. [A to Z]
if (this.Points == other.Points)
{
return this.Name.CompareTo(other.Name);
}
// Default to points sort. [High to low]
return other.Points.CompareTo(this.Points);
}
}
并测试它:
List<Player> list = new List<Player>();
list.Add(new Player() { Name = "Player1", Points = 50 });
list.Add(new Player() { Name = "Player2", Points = 60 });
list.Add(new Player() { Name = "Player3", Points = 30 });
list.Add(new Player() { Name = "Player4", Points = 80 });
list.Add(new Player() { Name = "Player5", Points = 70 });
list.Sort();
foreach (var element in list)
{
Console.WriteLine(element.Name);
}
结果如下: