Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort elements of array list in C#

Tags:

c#

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"

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.?

like image 298
SyncMaster Avatar asked May 12 '09 12:05

SyncMaster


People also ask

How do you sort elements in an ArrayList?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

How do you sort values in an array?

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

Is it possible to sort the elements of an array?

It is not possible to obtain sorted array.


1 Answers

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));

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));

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.

like image 123
John Feminella Avatar answered Sep 22 '22 00:09

John Feminella