Automatically Sort C# Objects

Whenever you create a C# class definition, consider adding one extra method so you can automatically sort object instances. It's easy and well worth the minimal extra effort. For example, suppose you've defined:

public class Employee
{
  public string name; 
  public string title; 
  // methods here
}

If you enhance the class as follows:

 
public class Employee : IComparable
{
  public string name; 
  public string title; 
  // Methods
  public int CompareTo(Employee other) 
  {
    return String.Compare(this.name, other.name); 
  }
}

Then if you have a list of objects:

List list = new List();

You can automatically sort this list with the statement:

list.Sort(); 

Being able to automatically sort lists and arrays of objects really comes in handy for WriteLine-style debugging and display routines.

Dr. James McCaffrey works for Microsoft Research in Redmond, Wash. He has worked on several Microsoft products including Internet Explorer and Bing.

Posted by James McCaffrey on 05/18/2015


Keep Up-to-Date with Visual Studio Live!

Email address*Country*