Sorting System.Collections.Generic.List<T>

This post shows the sorting technique using anonymous delegate that can be implemented in any custom type generic list based on the selected property.For sorting any custom type the class must implement the System.IComparable interface. Now let me assume you have a Person class and if you want to sort the list of person objects then you must implement System.IComparable interface and write the logic of how our person object is to be sorted in the CompareTo method

using System;

namespace ConsoleApplication1
{
    class Person : IComparable
    {
        public Person(string firstName, int age)
        {
            FirstName = firstName;
            Age = age;
        }

        public string FirstName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        // sorting in ascending order      

        #region IComparable Members

        public int CompareTo(object obj)
        {
            var person = (Person) obj;
            return FirstName.CompareTo(person);
        }

        #endregion
    }
}

But you can simplify the sorting just by using the anonymous delegate as shown bellow and you don’t need to implement IComparable interface

var persons = new List<Person>
                    {
                        new Person("Tom", 30),
                        new Person("Harry", 55)
                    };
// sort in ascending order
persons.Sort(delegate(Person person0, Person person1)
                    {
                        return person0.FirstName.CompareTo(person1.FirstName);
                    });
// sort in descending order
persons.Sort(delegate(Person person0, Person person1)
                    {
                        return person1.FirstName.CompareTo(person0.FirstName);
                    });

Technorati tags: generic, c#, code


 
 
 

5 Responses to “Sorting System.Collections.Generic.List<T>”

  1. sandrar
    10. September 2009 at 13:24

    Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

  2. Diego
    12. February 2010 at 19:23

    Muchas gracias por la info sobre los anonymous delegate. Me vino muy bien!

  3. Nishant
    26. August 2010 at 07:42

    Hi !!! Thanks it works… but i don’t understand second method it didn’t work for me.. :-(

  4. peter
    17. January 2011 at 20:36

    Thanks, this one helped me to solve the collection sort problem

  5. tarasn
    15. September 2011 at 10:23

    I use WordPress . ;-)

Leave a Reply