Monday, November 22, 2010

How to sort a list using a delegate

Sorting is a fundamental part software development. This post will review a technique of sorting generic lists with inline delegates.

First, let’s define an elementary class that we will collect and ultimately sort.

public class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

The following class, Family, will create a collection of persons and exposes two sorting methods. One method will sort the collection based on age and the other on name. These methods use inline delegates to specify the sorting logic, or more specifically, the logic to compare two individual people. Both methods use inline delegates but use slightly different syntax. The last method will print the names and ages of people in the collection. To print this information you must have your solution set to debug mode and “Debug” selected in the output window.

public class Family {
    public List<Person> _people = new List<Person>();
    public Family() {
        this._people = new List<Person>();
        this._people.Add(new Person() { Name = "Bob", Age = 43 });
        this._people.Add(new Person() { Name = "Jim", Age = 10 });
        this._people.Add(new Person() { Name = "Larry", Age = 15 });
        this._people.Add(new Person() { Name = "John", Age = 30 });
        this._people.Add(new Person() { Name = "Mary", Age = 8 });
    }
    public void SortFamilyByAge() {
        this._people.Sort(
            delegate(Person a, Person b) {
                return a.Age.CompareTo(b.Age);
            }
        );
    }
    public void SortFamilyByName() {
        this._people.Sort(
            (Person a, Person b) => {
                return a.Name.CompareTo(b.Name);
            }
        );
    }
    public void PrintFamily() {
        this._people.ForEach(
            p => {
                Debug.WriteLine(string.Format("{0} ({1})", p.Name, p.Age));
            }
        );
        Debug.WriteLine(Environment.NewLine);
    }
}

And finally, the following code will instantiate the family object and run the two sort methods, sort by age and sort by name.

Family family = new Family();
family.SortFamilyByAge();
family.PrintFamily();
family.SortFamilyByName();
family.PrintFamily();

The code will produce the following output.

How to sort a list using a delegate

No comments:

Post a Comment