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.