0

How do I order an ArrayList of objects by one of the objects attributes?

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

5 Comments

Hey ive tried your first suggestion and its telling me i need to use a delegate type? :s
I've doublechecked it and it works here. What framework version do you use? Can you post your code? What's the exact error message you get?
He's talking about ArrayList. Lambdas requires him to catch up with 3 updates and a whole bunch of reading. Lost cause, really.
@Tom: Make sure you are using Visual Studio 2008 or 2010. This will not work in 2005. @Hans: More than likely he is coming from Java..
Brilliant, concise and Works!
2

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 the Sort method with no arguments :

    arrayList.Sort();
    
  • otherwise, you need to create a custom comparer by implementing the IComparer interface :

    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());
    

Comments

0

Whenever you want to sort an array you need to compare it with a specific element of it. Suppose you have a List of array called Client and Client has clientID Now you want to sort it. Your code should be

Client.Sort(a, b) => string.Compare(a.clientID.ToString(), b.clientID.ToString()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.