如何排序的ArrayList(INT) [英] How to sort ArrayList(int)

查看:423
本文介绍了如何排序的ArrayList(INT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何排序的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.

这篇关于如何排序的ArrayList(INT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆