How to sort ArrayList(int)
18,053
Solution 1
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);
}
}
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.
Solution 2
You can use list.Sort() function. see example here http://msdn.microsoft.com/ru-ru/library/0e743hdt.aspx
Solution 3
You can you use ArrayList.Sort Method
Solution 4
ArrayList contains a Sort method. (Edited to remove incorrect .NET information)
Related videos on Youtube
Author by
Ram
Updated on June 04, 2022Comments
-
Ram almost 2 years
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?
-
Jon Skeet almost 13 yearsThat's not valid C# code (Add, not add). Why are you using the non-generic ArrayList type anyway? Are you using .NET 1.1 for some reason?
-
Ram almost 13 yearsYa. list.add(). that is wrong only sorry for that.I want to sort the arraylist since i'm dynamically adding the values in codebehind.Can u suggest someother collection which supports sorting
-
Jon Skeet almost 13 yearsNo, you mean
list.Add
.ArrayList
has always been sortable, but without knowing why you're using a non-generic type rather than the rather niceList<T>
it's hard to advise you well. -
Aisah Hamzah almost 13 yearsAnother question is, probably: what type of sort do you expect? Since each element is an object, do you want them compared as strings, or numerically?
-
-
Ram almost 13 yearsCan you explain me briefly or can u provide me any link
-
Mark Schadler almost 13 yearsSee this page for documentation of the ArrayList class. msdn.microsoft.com/en-us/library/… There you can find information on the Sort method. You will have to implement a comparator to sort in ASC vs DSC, however examples are provided in the documentation of this.
-
Jon Skeet almost 13 yearsIt's contained a Sort method since 1.0 - certainly in 1.1: msdn.microsoft.com/en-us/library/895sadkk(v=VS.71).aspx
-
Admin over 2 yearsYour answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.