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?
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.
You can use list.Sort() function. see example here http://msdn.microsoft.com/ru-ru/library/0e743hdt.aspx
ArrayList contains a Sort method. (Edited to remove incorrect .NET information)
Using an array list instead of List<int> here is dangerous, however, here is what you are looking for:
System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(5);
al.Add(3);
al.Add(1);
al.Add(4);
al.Add(0);
al.Sort();
foreach (var x in al)
{
Console.WriteLine(x.ToString());
}
al.Sort(new DescendingIntSorter());
foreach (var x in al)
{
Console.WriteLine(x.ToString());
}
public class DescendingIntSorter : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return ((int)y).CompareTo((int)x);
}
}
private void DisplayMain()
{
string sValue = "1,2,5,8,6,7,110,220";
txtValue.Text = sValue;
string[] asDS = sValue.Split(',');
ArrayList alData = new ArrayList();
foreach (string sDS in asDS)
{
alData.Add(sDS);
}//end of foreach
alData.Sort(new IntSort());
//============
int iCnt = 0;
StringBuilder sbResult = new StringBuilder();
foreach (string sData in alData)
{
iCnt++;
sbResult.AppendLine(iCnt.ToString() + " ====> " + sData);
}//end of if
string sResult = sbResult.ToString();
txtResult.Text = sResult;
}//end of DisplayMain
public class IntSort : IComparer
{
public int Compare(object x, object y)
{
string sX = x.ToString();
string sY = y.ToString();
int iResult = 0;
int iX = int.Parse(sX);
int iY = int.Parse(sY);
if(iX > iY) { iResult = 1; }//end of if
else if (iY > iX) { iResult = -1; }//end of if
return iResult;
//return ((int)y).CompareTo((int)x);
}
}
list.Add.ArrayListhas 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.