如何排序的ArrayList(INT)ArrayList、INT

2023-09-03 22:31:40 作者:奔溃边缘

我如何排序的ArrayList 升序和降序订单。 示例。

How can I sort the Arraylist in ascending and descending orders. Example.

ArrayList list= new ArrayList();
list.Add(2);
list.Add(8);
list.Add(0);
list.Add(1);

我如何排序上面的列表中的升序和降序排列?

How can I sort the above list in both ascending and descending order?

推荐答案

您可以使用 list.Sort()为升序排列。对于降序排列,则需要通过实施的IComparer 扭转秩序。像这样的东西会做:

You can use list.Sort() for ascending order. For descending order, you need to reverse the order by implementing IComparer. Something like this will do:

// calling normal sort:
ArrayList ascendingList = list.Sort();

// calling reverse sort:
ArrayList descendingList = list.Sort(new ReverseSort());

// implementation:
public class ReverseSort : IComparer
{
    public int Compare(object x, object y)
    {
        // reverse the arguments
        return Comparer.Default.Compare(y, x);
    }

}

需要注意的是,像乔恩斯基特提到下的主要问题的意见线程,则不需要使用无类型的ArrayList的。相反,你可以使用通用的名单,其中,T> ,这是类型安全而仅仅是更通用

Note that, like Jon Skeet mentions in the comment thread under the main question, you do not need to use the untyped ArrayList at all. Instead, you can use the generic List<T>, which is typesafe and is simply more versatile.