Home » C# » How to sort a C# List

How to sort a C# List

By Emily

Further to my post all about adding items to a C# list, this post explains how to sort a C# List (descending and ascending). I’ll include code examples of sorting a C# list of strings or integers, and will explain how to sort custom type lists. You may be trying to sort a C# list of custom objects and be receiving an error message that says something like “ArgumentException: At least one object must implement IComparable“, in which case this post will help you.

How to sort a C# List of integers

Let’s start with a list of integers:

List<int> tickets = new List<int> { 54, 12, 3, 41, 15, 16, 702, 89, 109 };

Now we want to sort that list of ints, so we use the Sort method and by default it sorts the list in ascending value order :

tickets.Sort();

After sorting the C# list, the List order would change as shown here:

how to sort a C# list

If we now do the same thing on a List of strings…

How to sort a C# List of strings

List<string> sports = new List<string> { "Tennis", "Baseball", "Swimming", "Skiing", "Running", "Karate" };

sports.Sort();

The list of strings is sorted alphabetically ascending by default.

sort a c# list of strings

C# Sort List Descending

So that’s covered how to sort a list by its default order – ascending. What if we want to sort the list in descending order? It takes two steps, one to sort, and one to reverse the default order:

sports.Sort();
sports.Reverse();

How to sort a Custom C# List by a property

At the end of my previous post on using a C# List, our list contained a drinks order, and looked like this:

//The List now
501: Orange Juice
312: Champagne
43: Martini
44: Mojito
18 Pale Ale
502: Apple Juice
74: Coke
88: Sparkling Water

If you call the Sort method on this list – drinks.Sort() – you’ll get an Exception:

System.InvalidOperationException: 'Failed to compare two elements in the array.'

Inner Exception:
ArgumentException: At least one object must implement IComparable.

It doesn’t know how to sort the list, because we haven’t told it enough about our object yet. So how do we sort a custom list? First of all you have to decide in theory how you want your list to be sorted. Do we want to sort it by Name, or by ID? Or maybe we’ll want to be able sort by either. In this case we will write both. We will write a custom comparer which will be used to sort the object when specified in the Sort method.

Using a Custom Comparer to sort a List of objects

Looking at our custom object Drink, we’ll add a Custom Comparer called CompareByName, which as the name suggests, will sort the drinks by the Name property. Here is the Drink class :

 internal class Drink
 {
   	public string Name { get; set; }
	public int Id { get; set; }

    public static int CompareByName(Drink drink1, Drink drink2)
    {
      return String.Compare(drink1.Name, drink2.Name);
    }
}

If you now call the Sort method on the C# list, and specify the custom comparer…..

drinks.Sort(Drink.CompareByName);

…you will see that it’s now ordered alphabetically by drink Name.

Sort C# list of objects by property using custom comparer

Now let’s update the Drink class and add another custom comparer, this one will sort the list of drinks by their id.

internal class Drink
{
    public string Name { get; set; }
    public int Id { get; set; }

    public static int CompareByName(Drink drink1, Drink drink2)
    {
      return String.Compare(drink1.Name, drink2.Name);
    }

    public static int CompareById(Drink drink1, Drink drink2)
    {
      return drink1.Id.CompareTo(drink2.Id);
    }
}


And to use it we again call the Sort method on the C# list, and specify which comparer to use:

drinks.Sort(Drink.CompareById);

However although this provides you with a way of sorting your list if you call the default Sort method on your drinks list, you’ll still see that same Exception.

Using IComparable to Sort a list of objects

If you want to just be able to call the Sort method and have your list of objects sorted in a particular way, you need to implement IComparable on the class and then define a way to sort your objects in the CompareTo method. So in this case our Drinks class would become :

   internal class Drink : IComparable
    {
        public string Name { get; set; }
        public int Id { get; set; }
 
        public int CompareTo(object obj)
        {
            if (obj == null) return 1;

            Drink drinkToCompare = obj as Drink;
            
            if (drinkToCompare.Id < Id)
            {
                return 1;
            }
            if (drinkToCompare.Id > Id)
            {
                return -1;
            }

            // The drink ids are the same
            return 0;
        }

    }

… and calling drinks.Sort() now results in no Exception, and the list is sorted by ID’s like this:

****** Drinks ******
9: Sambucca
17: Vodka and orange
18: Pale Ale
43: Martini
44: Mojito
192: Prosecco
--------------------------

Summary

Now you know how to sort C# list of objects using a custom comparer and by implementing IComparable on a class. You can also use linq, but I’ll cover that in a separate post.

You may also be interested in: