C#.NET: Sorting A Generic Collection

This is a sample console application demonstrating a quick way to sort a generic collection. The relevant line is


list.Sort(delegate(Person x, Person y) { return String.Compare(x.LastName, y.LastName);});

The example sorts a List of Person objects by the LastName property.


using System;
using System.Text;
using System.Collections.Generic;

namespace ConsoleApplication1
{
   public class Person
    {
        private String firstName;
        public String FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        private String lastName;
        public String LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }

        private int age;
        public int Age
        {
           get { return age; }
           set { age = value; }
        }
 
        public Person()
        {
        }

        public Person(String fname, String lname, int age)
        {
            this.FirstName = fname;
            this.LastName = lname;
            this.Age = age;
        }

        public override string ToString()
        {
            return String.Format("{0}, {1} Age: {2}", this.LastName, this.FirstName, Convert.ToString(this.Age));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<Person> list = new List<Person>();
            list.Add(new Person("John", "Doe", 32));
            list.Add(new Person("Jane", "Doe", 30));
            list.Add(new Person("Bugs", "Bunny", 50));
            list.Add(new Person("Yosemite", "Sam", 60));

            // display current list
            Console.WriteLine("BEFORE SORT");
            foreach (Person p in list)
            {
                Console.WriteLine(p);
            }

            // sort by Last Name
            list.Sort(delegate(Person x, Person y) { return String.Compare(x.LastName, y.LastName);});

            // display after sort
            Console.WriteLine(Environment.NewLine + "AFTER SORT");
            foreach (Person p in list)
            {
                Console.WriteLine(p);
            }
            Console.WriteLine();
            Console.Read();
        }
    }
}

Tags: , , ,

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

3 Responses to “C#.NET: Sorting A Generic Collection”

  1. Jesse Slicer says:

    Just as a FYI, your sort line

    list.Sort(delegate(Person x, Person y) { return String.Compare(x.LastName, y.LastName);});

    can be simplified in VS 2008 (C# 3.0) with a lambda expression as such

    list.Sort((x, y) => string.Compare(x.LastName, y.LastName));

  2. kaeli says:

    Sweet. =)

    We still use 2.0 at work, so I haven’t had too much time to check out the new 3.0 features yet.

  3. Jesse Slicer says:

    Two of the other niftier things in C# 3.0 are “auto properties” where

    private String firstName;
    public String FirstName
    {
    get { return firstName; }
    set { firstName = value; }
    }

    can be abbreviated as

    public String FirstName
    {
    get;
    set;
    }

    the compiler will generate the backing member automatically.

    The other is called (I think) Initializers and it can transform this code

    List list = new List();
    list.Add(new Person(”John”, “Doe”, 32));
    list.Add(new Person(”Jane”, “Doe”, 30));
    list.Add(new Person(”Bugs”, “Bunny”, 50));
    list.Add(new Person(”Yosemite”, “Sam”, 60));

    into this code

    List list = new List
    {
    new Person(”John”, “Doe”, 32),
    new Person(”Jane”, “Doe”, 30),
    new Person(”Bugs”, “Bunny”, 50),
    new Person(”Yosemite”, “Sam”, 60),
    };

Leave a Reply