如何排序在C#中的数组列表元素 [英] How to sort elements of array list in C#

查看:127
本文介绍了如何排序在C#中的数组列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个ArrayList

I have an ArrayList that contains,

[0] = "1"
[1] = "10"
[2] = "2"
[3] = "15"
[4] = "17"
[5] = "5"
[6] = "6"
[7] = "27"
[8] = "8"
[9] = "9"

现在我需要排序的数组列表,这样就变成,

Now i need to sort the array list such that it becomes,

[0] = "1"
[1] = "2"
[2] = "5"
[3] = "6"
[4] = "8"
[5] = "9"
[6] = "10"
[7] = "15"
[8] = "17"
[9] = "27"

最后,我还要从越来越价值观ArrayList和使用它们作为'诠释'值。我怎样才能做到这一点?还是我将它们转换为先诠释,然后对它们进行排序。

At last i will be getting the values from ArrayList and using them as 'int' values. How can i do this? Or shall i convert them to int at first and then sort them.?

推荐答案

如果您可以确保该列表只包含字符串可以转化为整数,然后用 的IEnumerable< T&取代。排序依据 扩展方法,试试这个:

If you can be sure the list contains only strings that can be transformed to integers, then with the IEnumerable<T>.OrderBy extension method, try this:

var sortedList = list.OrderBy(item => int.Parse(item));

如果您使用的是的ArrayList 代替的列表<串> ,你需要铸造第一(嘘!):

If you're using an ArrayList instead of a List<string> (boo!), you'll need to Cast first:

var sortedList = list.Cast<string>().OrderBy(item => int.Parse(item));

您也可以定义自己的比较器作为JaredPar指出,但国际海事组织这东西,这是一个大量的工作已经实施。但是,它的效率更高。

You can also define your own comparer as JaredPar noted, but IMO that's a lot of work for something that's already implemented. However, it's more efficient.

这篇关于如何排序在C#中的数组列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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