【发布时间】:2015-08-26 20:02:37
【问题描述】:
我有一个 ArrayList,其中存储 10 个对象,每个对象有两个随机生成的数字,我想按对象的 Y 值对列表进行排序。
Random rndm = new Random();
ArrayList CustomList = new ArrayList();
for (int i = 0; i < 10; i++)
{
Point LP = new Point(rndm.Next(50), rndm.Next(50));
CustomList.Add(LP);
}
PrintList(CustomList);
CustomList.Sort();
PrintList(CustomList);
Sort 方法抛出以下异常:
System.InvalidOperationException: The comparer threw an exception. ---> System.ArgumentException: At least one object must implement IComparable.
我认为它不起作用,因为 Sort 方法无法处理 ArrayLists 中的二维对象。我怎样才能让 Sort 方法现在起作用?
【问题讨论】:
-
为什么不用
List<Point>而不是ArrayList? -
您如何期望 Sort 方法知道您想按 Y 而不是 X 排序?使用
List<point>和list = list.OrderBy(t=>t.Y).ToList();。你不应该再使用 ArrayList 了,现在有像List<T>这样的不错的通用集合。
标签: c# sorting icomparable