如何对 ArrayList(int) 进行排序 [英] How to sort ArrayList(int)

查看:50
本文介绍了如何对 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);
    }

}

请注意,就像 Jon Skeet 在主要问题下的评论线程中提到的那样,您根本不需要使用无类型的 ArrayList.相反,您可以使用通用的 List,它是类型安全的,而且用途更广.

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天全站免登陆