How do I order an ArrayList of objects by one of the objects attributes?
3 Answers
ArrayList is somewhat deprecated. We use the generic List<T> class now.*
You can sort a List<T> in-place using List<T>.Sort:
List<Person> persons = // ...
persons.Sort((a, b) => string.Compare(a.Name, b.Name));
or create a new List<T> using LINQ's Enumerable.OrderBy:
List<Person> persons = // ...
List<Person> sortedPersons = persons.OrderBy(p => p.Name).ToList();
(* Unless you're stuck with .NET Framework 1.1)
5 Comments
As dtb explained, you should probably use a generic List<T> than an untyped ArrayList unless you're using a pre 2.0 version of .NET.
If you really want to do it with an ArrayList, there are two way of doing it :
if the elements of the collection implement
IComparable, just use theSortmethod with no arguments :arrayList.Sort();otherwise, you need to create a custom comparer by implementing the
IComparerinterface :public class PersonComparer : IComparer { public int Compare(object a, object b) { Person pa = a as Person; Person pb = b as Person; if (pa == pb) return 0; if (pa == null) return -1; if (pb == null) return 1; return string.Compare(pa.Name, pb.Name); } } ... arrayList.Sort(new PersonComparer());