I have an arraylist. it keeps arraylists in it. For example;
ar1 -> {2,3,46,67} keeps 4 members.
ar2 -> {28,96,67} keeps 3 members.
ar2 -> {56,32,67,54,214} keeps 5 members.
Ar_main[0]= ar1
Ar_main[1]= ar2
Ar_main[2]= ar3
i want to sort ar_main order by count of members. i used bubble sort algorithm. but it didn't work, can't we sort arraylist like this method?
private void sortArrayToAscending(ArrayList ar)
{
ArrayList ar1,ar2;
for (int i = 0; i < ar.Count - 1; i++)
for (int j = 1; j < ar.Count - i; j++)
{
ar1 = (ArrayList)ar[j];
ar2 = (ArrayList)ar[j-1];
if (ar1.Count < ar2.Count)
{
ArrayList temp = ar2;
ar2=ar1;
ar1=temp;
}
}
}
There is a built-in Sort
method in the ArrayList
that does the sorting for you. What you have to provide is an IComparer
implementation that compares the list, making their length the criteria:
public void ArrayListSort()
{
var list = new ArrayList();
list.Sort(new LengthComparer());
}
class LengthComparer : IComparer
{
public int Compare(object x, object y)
{
var a = x as ArrayList;
var b = y as ArrayList;
// check for null if you need to!
return a.Count.CompareTo(b.Count);
}
}
However, unless you're actually using .NET 1.1, I'd recommend that you use List<T>
instead of ArrayList
, and the LINQ OrderBy
method. This is type-safe, and I'd consider it more idiomatic C# nowadays. On top of that, it's way shorter:
var typedList = new List<List<int>>();
var sortedList = typedList.OrderBy(i => i.Count).ToList();
Be aware that the former is an in-place sort (altering the original list), whereas the latter copies the result into a new list.