Switch On The Code RSS Button - Click to Subscribe
May
6

C# Snippet Tutorial - Custom List Sorting

The List is one of my favorite additions to the .NET framework. It has built-in mechanisms to perform efficient sorting and searching. In this snippet tutorial, I'm going to demonstrate how to customize the sorting routines used by the List class.

The default Sort function of the List uses the CompareTo method of the object if it implements IComparable. Fortunately, the .NET primitives already implement this interface, which means to sort a List of primitives, you don't have to do anything special.


List<string> myList = new List<string>();

myList.Add("one");
myList.Add("two");
myList.Add("three");
myList.Add("four");

myList.Sort();

foreach (string s in myList)
  Console.WriteLine(s);

// output:
// four
// one
// three
// two

With that being said, to get the List to sort your own custom objects, all you'd have to do is have your object implement the IComparable interface.

public class MyObject : IComparable<MyObject>
{
  private int _myInt;

  public int MyInt
  {
    get { return _myInt; }
    set { _myInt = value; }
  }

  public MyObject(int value)
  {
    _myInt = value;
  }

  public int CompareTo(MyObject obj)
  {
    return _myInt.CompareTo(obj.MyInt);
  }
}

And here's what happens when you populate and sort a list of these objects.

List<MyObject> myObjectList = new List<MyObject>();

myObjectList.Add(new MyObject(3));
myObjectList.Add(new MyObject(1));
myObjectList.Add(new MyObject(4));
myObjectList.Add(new MyObject(2));

myObjectList.Sort();

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);

// output:
// 1
// 2
// 3
// 4

That works great when you have access to the object, but what happens if you want to sort an object that doesn't implement IComparable? Good thing for us, the Sort method can take an IComparer, which will take its place. If the object that is being sorted also implements IComparable, passing an IComparer will override the CompareTo function located inside the object.

Let's specify an IComparer that will sort the previous List in the opposite direction.

public class MyListSorter : IComparer<MyObject>
{
  public int Compare(MyObject obj1, MyObject obj2)
  {
    return obj2.CompareTo(obj1);
  }
}

Just like with the CompareTo function, the Compare function returns less than zero if the first object precedes the second one, 0 if they are identical, and greater than zero if the second object precedes the first. Since I'm comparing primitive types, I simply used their CompareTo function. Here's how we use this object.

myObjectList.Sort(new MyListSorter());

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);

// output:
// 4
// 3
// 2
// 1

If you don't want to go through all the work of creating a new object to do your comparisons, the last way to sort a List is to use a function. Here's the same sorting using a Comparison delegate.

public int MySortFunction(MyObject obj1, MyObject obj2)
{
  return obj2.CompareTo(obj1);
}

myObjectList.Sort(new Comparison<MyObject>(MySortFunction));

foreach (MyObject obj in myObjectList)
  Console.WriteLine(obj.MyInt);

// output:
// 4
// 3
// 2
// 1

That's it for sorting a List. The sort function has another override not shown here that specifies the range to sort, but I'm sure you can figure out how to use that by yourself. If you have any questions or comments about sorting a List, leave them below.



Posted in C#, All Tutorials by The Reddest |

6 Responses

  1. Alex Says:

    Great article buddy!!
    I’ve just one question. In your example, your MyObject object contains an int property but when I try to do the same in my solution it says that the property does not contain a definition for “CompareTo”.
    What I’ve missed?

    Thanks!!

  2. Michael Reynolds Says:

    Great article. I am missing something though. I understand how to add, insert and remove items but is there a way to add “columns”? I want to add a “unit price” column to my list and access and populate the new field in each record??

  3. The Reddest Says:

    A List is a linear collection of objects. If you want a unit price, you’d have to add it as a property to the object stored in the list. If you actually want columns, consider using a DataTable instead of a List.

  4. can Says:

    I tried to sort with the way you do with MyListSorter class. The reason why I use this with a class based comparison is that, I need to compare different properties at different stages of the program. My array list inherits from a class, so i defined as:
    public class MyListSorter: IComparer

    and when i call the sort method in the main with individuals.Sort(new MyListSorter());

    I get 2 errors saying Comparer has wrong arguments and 2nd cannot convert from MyListSorter to System.Collections.IComparer

    What do you reckon?
    Thnx

  5. The Reddest Says:

    It sounds like you didn’t implement the IComparer interface on the MyListSorter class.

    public class MyListSorter : IComparer<MyObject>

  6. can Says:

    public class MyListSorter:IComparer

    public class IntArrayCH:IChromosome

    public interface IChromosome : IComparable

    Instead of storing IntArrayCH objects in List, when I stored in an array of that class. And it worked, but no Dynamic length:s

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Powered by WP Hashcash