Updated on

In C#, every way of sorting a List<T> comes down to where the comparison lives: in the type itself with IComparable<T>, in a separate comparer with IComparer<T> or Comparer<T>, or in a Comparison<T> delegate. List<T>.Sort() takes all three.

Sorting a collection is a common task, and C# gives us a variety of ways to do it. We’ll walk through each of them on the same small data set. If all we need is to sort by one property, a one-line OrderBy() is often enough, and our article on sorting a list of objects by property covers that case. Here we write the comparers ourselves.

Along with exploring different techniques for sorting a list, we will also implement our own custom MySortedList class which will allow us to maintain a list of data in a sorted fashion.

With that in mind, let’s dive into some code.

To download the source code for this article, you can visit our GitHub repository.

Setting Up Our Example Code

First, let’s create a simple record that we can use to explore the different options and techniques for sorting a list:

public sealed record Product(string ProductName, string Category, decimal Price)
{
    public Guid Id { get; init; } = Guid.NewGuid();
}

Second, let’s generate some sample data, which we can use to demonstrate the different techniques for sorting a list:

var products = new Product?[]
{
    new("Gorgeous Fish", "Games", 103.07m) { Id = Guid.Parse("f0569e86-bfad-6f3a-b74d-2555175dcc6e") },
    new("Tasty Cheese", "Clothing", 134.74m) { Id = Guid.Parse("4af80b60-3e17-1dfd-8462-c009ca918154") },
    null,
    new("Handcrafted Hat", "Books", 38.09m) { Id = Guid.Parse("c7b30b28-db07-f2ae-70dc-9505096e676b") },
    new("Practical Chicken", "Electronics", 126.06m) { Id = Guid.Parse("d6fee4b9-8767-851a-b386-a8af727663a7") },
    new("Generic Car", "Games", 75.18m) { Id = Guid.Parse("c65100fd-e49f-f5e0-0e71-052d7eefe9b3") }
};

As a side note, we have generated this data using the Bogus NuGet package. To learn more about Bogus and how it can be used to generate “realistic” testing data, be sure to check out our article on generating test data with Bogus.

Formatted nicely, our unsorted data looks like this:

Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3

So let’s dive in and begin exploring the different options available to us for sorting.

Setting a Default Sort Order With IComparable<T>

The IComparable<T> interface provides a mechanism for defining the default comparison behavior of a class. When defining a new class, that we wish to be sortable, we implement this interface to define the default sorting order.

The IComparable<T> interface defines a single method that we need to implement:

public int CompareTo (T? other)

The value returned indicates the relative positioning of the two objects within the desired sort order:

  • < 0 – the instance precedes other in the sort order
  • 0 – the instance is in the same position as other in the sort order
  • > 0 – the instance follows other in the sort order

When implementing IComparable<T> we should also override Equals() and overload the comparison operators <, <=, >, >= to maintain consistency with the results of CompareTo(). When overriding Equals() it is good practice to also overload the equality and inequality operators == and !=.

For more information concerning overriding Equals() and operator overloading, you can check out our article on operator overloading in C#. 

For simplicity’s sake and to keep the focus of our article on sorting, we are using a record rather than a class, which handles the equality overriding for us. You can read more about the record type in our article on C# records. 

Implementing IComparable<T>

Now, let’s take a look at implementing the IComparable<T> interface on our Product record. First, we will change our record signature to include the IComparable<T> interface, along with the non-generic IComparable interface:

public sealed record Product(string ProductName, string Category, decimal Price) : IComparable<Product>, IComparable

First, let’s take a look at our IComparable<Product> implementation. We will focus on sorting Products based primarily on the ProductName and only secondarily sort based on the Price:

public int CompareTo(Product? other)
{
    if (ReferenceEquals(this, other)) return 0;
    if (other is null) return 1;

    var nameComparison = string.Compare(ProductName, other.ProductName,
        StringComparison.OrdinalIgnoreCase);

    return nameComparison != 0 ? nameComparison : Price.CompareTo(other.Price);
}

The first thing we do on line #3 is to perform a reference comparison to check if we are comparing the same object with itself. If that is the case, we return 0, indicating that the objects occur in the same position within the sort order. Note that we did not say that a return value of 0 indicates equality, only their relative positioning within the sort order. Equal objects must return 0, but it is possible, based on how we are sorting, to have two unequal objects that still share the same position in relation to their sort order.

Second, on line #4 we check whether other is null. In the case of it being null, we return 1 indicating that our current object is larger than the null object.

Third, on line #6 we compare the ProductName of the two objects. Since we have already verified that they are not the same object and that other is not null, we can safely make this comparison.

This leads us to the last line, #9, where we check to see if the ProductName has the same sort-order positioning. If it does, then we compare the Price as a way of determining which object should be first in the sort order.

The non-generic IComparable in our signature needs its own public int CompareTo(object? obj), or the record does not compile. Ours returns 1 for null, passes a Product on to the method above and throws an ArgumentException for anything else.

IComparable<T> Implementation In Action

Now let’s see what happens when we sort our Product collection:

var productList = new List<Product?>(products);
productList.Sort();

Let’s inspect the result:

NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154

Sorting in a Different Order With IComparer<T>

Sometimes when we are sorting, we do not want to follow the default sort defined for a given type T. The IComparer<T> interface is one of the techniques we can use for sorting a list according to our own desired sort order. It allows an implementing type to define a Compare() method that can be used to sort objects of type T. The Compare() method signature is very similar to the CompareTo() method that we looked at with the IComparable<T> interface:

public int Compare (T? a, T? b)

Just like the CompareTo() method, the value returned indicates the relative positioning of the two objects within the desired sort order:

  • < 0 – a precedes b in the sort order
  • 0 – a is in the same position as b in the sort order
  • > 0 – a follows b in the sort order

A common use case for the IComparer<T> is to define a custom comparer to use for sorting a collection differently than the default ordering defined by the object. For example, the default sort ordering of our Product object is based on the natural ordering of the ProductName. We can override that behavior when sorting a collection by defining an IComparer<Product> that sorts based on the price.

Implementing IComparer<T> for Custom Sorting

Let’s take a look at it in action. We’ll start with our class definition:

public sealed class ProductPriceIComparer : IComparer<Product?>

The only thing left to do is to implement the Compare(Product? x, Product? y) method:

public int Compare(Product? a, Product? b)
{
    if (ReferenceEquals(a, b)) return 0;
    if (a is null) return -1;
    if (b is null) return 1;

    var priceComparison = a.Price.CompareTo(b.Price);

    return priceComparison != 0 ? priceComparison :
        string.Compare(a.ProductName, b.ProductName, StringComparison.OrdinalIgnoreCase);
}

The code looks very similar to the CompareTo() method that we defined earlier, with one very notable difference, the number of arguments. CompareTo() is a member of the Product class and so only takes a single argument, namely the other Product to compare with the current Product. When we implement the IComparer<T> interface, the Compare() method performs the comparison with two provided Product objects. 

First, on line #3, we check whether the two objects are the same object. In that case, we just return 0. Next, on line #4, we check to see if a is null. If it is, then we return -1 indicating that a comes before b in the sorting order. On line #5 we also check whether b is null and if it is, we return 1 to indicate that b comes before a in the sorting order.

The major difference between our earlier CompareTo() and this Compare() is found on lines 7 and 9. In our CompareTo() method, we first performed a comparison on the ProductName and then, only if the ProductName was equal regarding sort order, did we compare the Price. In this case, we are checking the Price first, as our goal is to order Products according to Price rather than ProductName. 

IComparer<T> Implementation in Action

Let’s see our collection when we sort it using the ProductPriceIComparer:

var productList = new List<Product?>(products);
productList.Sort(new ProductPriceIComparer());

And, let’s check the result:

NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154

Why Derive From the Comparer<T> Abstract Class?

Comparer<T> is an abstract base class that already implements IComparer<T>. Deriving from it costs us one method override, and we get two things the bare interface does not give us.

Microsoft’s documentation for IComparer<T> puts the choice plainly: “We recommend that you derive from the Comparer<T> class instead of implementing the IComparer<T> interface”. The reasons it gives are those two extras.

The first is the non-generic IComparer interface. Comparer<T> implements it explicitly, so our comparer also works with older APIs that take a plain IComparer, such as ArrayList.Sort(), with no extra code.

The second is the static Default property. Comparer<T>.Default returns the comparer that uses the type’s own IComparable<T> implementation, and it deals with null for us: null sorts before any object, and two null values compare as equal.

There is also a static Create() method that turns a lambda into a complete comparer object. We’ll use it at the end of this section.

Deriving from Comparer<T>

So let’s take a look at creating a custom comparer to sort our Product items by Id via the Comparer<T>:

public sealed class ProductIdComparer : Comparer<Product?>

Since we are looking to implement a comparer for the Product class, we derive from the generic Comparer<T> class passing in Product for our generic type argument.

Next, we need to implement Compare(), just like we did when implementing the IComparer<T> interface:

public override int Compare(Product? a, Product? b)
{
    // removed for brevity
    return a.Id.CompareTo(b.Id);
}

For brevity, we have omitted the first three lines of the method, as they are identical to lines 3-5 in the IComparer<T> implementation. In our case, we are defining a comparison based on the Id of the Product. With this as our goal, all we need to do is return the result of the Id comparison.

One important difference to note between implementing the IComparer<T> interface and deriving from Comparer<T> is the signature of the Compare() method. When implementing the interface, we simply define a public Compare() method. When deriving from the base class, we have to override the Compare() method.

Comparer<T> Implementation in Action

Let’s take a look at our Id comparer in action:

var productList = new List<Product?>(products);
productList.Sort(new ProductIdComparer());

The result:

NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e

Creating a Comparer From a Lambda With Comparer<T>.Create

We don’t always need a whole class for a comparer. The static Comparer<T>.Create() method takes a Comparison<T> lambda and wraps it in a Comparer<T> object for us.

Let’s sort our products by price, highest first:

var byPriceDescending = Comparer<Product?>.Create(
    (a, b) => Nullable.Compare(b?.Price, a?.Price));

var productList = new List<Product?>(products);
productList.Sort(byPriceDescending);

Here, b?.Price and a?.Price give us a decimal? that is null for a missing product. Nullable.Compare() treats null as smaller than any value, and because we pass b first, the order is descending and the null entry ends up last:

Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000

Sort() also accepts a lambda directly, so why wrap it? Because some APIs take only an IComparer<T>: the range overload of Sort() we look at shortly, BinarySearch(), and the constructor of our MySortedList<T> class. Comparer<T>.Create() is how a lambda gets into any of them.

Sorting With the Comparison<T> Delegate

Now, let’s take a look at the Comparison<T> delegate. This delegate is one of the techniques we can employ when sorting a list. The following signature defines it:

public delegate int Comparison<in T>(T a, T b);

Just like our other comparison methods (CompareTo() and Compare()), the Comparison<T> delegate returns an int based on the sort order of compared objects:

  • < 0 – a precedes b in the sort order
  • 0 – a is in the same position as b in the sort order
  • > 0 – a follows b in the sort order

To use the Comparison<T> delegate, we simply invoke the Sort() overload that accepts the delegate. We can accomplish this either by passing in a lambda function directly or by defining a method that matches the delegate signature. Let’s look at both options.

Defining Comparison<T> Delegate via a Lambda

Here we’ll invoke Sort() with a lambda that orders our Product items by Category:

var productList = new List<Product?>(products);
productList.Sort((a, b) =>
{
    // object and null checks removed for brevity
    var result = string.Compare(a.Category, b.Category, StringComparison.OrdinalIgnoreCase);

    return result != 0 ? result : a.CompareTo(b);
});

Once again for brevity, we removed the object and null checks from the code listing, as they are identical to our earlier example. Following those checks, we perform a comparison of the Category property. If a and b share the same category, we fall back to the default comparison (ProductName, followed by Price).

Now let’s take a look at the result:

NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e

Defining Comparison<T> Delegate via a Method

As we mentioned earlier, we can also define a method that matches the Comparison<T> delegate signature and pass that as the argument to the Sort() overload, which takes a Comparison<T>. Let’s see how this works by defining a new static DescendingCompare() method in our Product class:

public static int DescendingCompare(Product? a, Product? b) => Comparer<Product>.Default.Compare(b, a);

This method is pretty straightforward. Our goal is to sort Products in descending order, so all we need to do is “reverse” the comparison result of the current CompareTo() implementation. We accomplish this by reversing the operands when performing the comparison. That is, instead of comparing a to b, we compare b to a.

We go through Comparer<Product>.Default instead of calling b.CompareTo(a) ourselves because the default comparer also handles null. A null product sorts below every other product, so in descending order it ends up last. Two null values compare as equal.

A shorter version, b?.CompareTo(a) ?? -1, gets the two-null case wrong. It returns -1, and a comparer must return 0 when it compares two equal items. With the single null in our sample data, nobody would notice. When we sorted 200 products, 40 of them null, with that version, Sort() threw an ArgumentException complaining that the comparer returns inconsistent results.

Now let’s put it to use:

var productList = new List<Product?>(products);
productList.Sort(Product.DescendingCompare);

And the results:

Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000

How Do We Sort Only Part of a List?

To sort only part of a list, we call the Sort() overload that takes a starting index, a count and a comparer. It sorts count elements beginning at index, and every element outside that range stays exactly where it was.

The comparer may be null. In that case, Sort() falls back to Comparer<T>.Default, which uses the type’s own IComparable<T> implementation. If T has no default comparison at all, the call throws an InvalidOperationException.

Two details catch people out. First, this overload has no version that takes a Comparison<T> delegate, so a lambda has to go through Comparer<T>.Create() before it can be passed in.

Second, the range has to fit inside the list. A negative index or count throws an ArgumentOutOfRangeException, and a range that runs past the end of the list throws an ArgumentException.

A typical use is a list with a pinned group of items at the top that should stay where they are while we sort the rest.

The method signature is as follows:

List<T>.Sort(int index, int count, IComparer<T>? comparer)

Now, let’s see this overload of Sort() in action. We will sort the first 3 elements of our sample list by Price, which is handled by our previous implementation ProductPriceIComparer, and the last 3 using the default Product comparison:

var productList = new List<Product?>(products);
productList.Sort(0, 3, new ProductPriceIComparer());
productList.Sort(3, 3, null);

And the results:

NULL                          NULL                $0.00          00000000-0000-0000-0000-000000000000
Gorgeous Fish                 Games               $103.07        f0569e86-bfad-6f3a-b74d-2555175dcc6e
Tasty Cheese                  Clothing            $134.74        4af80b60-3e17-1dfd-8462-c009ca918154
Generic Car                   Games               $75.18         c65100fd-e49f-f5e0-0e71-052d7eefe9b3
Handcrafted Hat               Books               $38.09         c7b30b28-db07-f2ae-70dc-9505096e676b
Practical Chicken             Electronics         $126.06        d6fee4b9-8767-851a-b386-a8af727663a7

How Do We Keep a List Sorted With BinarySearch?

So far, every technique sorted a list in place, after the fact. To keep a List<T> sorted all the time, we never call Sort() after an insert. We ask BinarySearch() where the new item belongs and insert it there.

BinarySearch() only works on a list that is already sorted. When it finds the item, it returns its index. When it doesn’t, it returns a negative number, the bitwise complement of the index where the item would go, and the ~ operator turns that back into the insertion index.

Each search takes O(log n) comparisons. The insert is the expensive part: List<T> stores its items in one array, so Insert() shifts every element after the insertion point by one place.

Why not use a built-in sorted collection? SortedSet<T> drops duplicates, and SortedList<TKey, TValue> needs unique keys and stores key-value pairs. When we want duplicates and plain index access, a thin wrapper around List<T> is the simplest fit.

If one of them fits better, we cover SortedSet and SortedList in their own articles.

To make dealing with the behavior a bit clearer, we will create a custom MySortedList<T> class, which under the hood, will still use List<T>, but will maintain it in a sorted state. For brevity, we will not explore the entire class here.

Class Definition for Custom Sorting

First, let’s take a look at our class definition:

public sealed class MySortedList<T> : IList<T> where T : IComparable<T>

Because our goal is to maintain the sort order of our collection, we are restricting our type parameter T to those that implement IComparable<T>. Since we are creating a special type of list, we will also implement the IList<T> interface, so that we can use our sorted list in most places where we would use a standard List<T>.

Having said that, the fact that this list will always maintain a sorted order does add a couple of restrictions regarding the IList<T> interface. Namely, there are a couple of methods in the interface that we will not implement, but rather throw a NotSupportedException.

The first one is the Insert(int index, T item) method. Since our requirement is that our list is always sorted, we cannot support inserting at a specific index. Secondly, and related to the insert issue, is allowing set() through the indexer []. Retrieving a value at a given index is fully supported, but we cannot support setting the value, as that could lead to the list becoming unsorted.

Constructor Definitions

Just like List, we allow setting the initial capacity of the list through the constructor. Because we are maintaining the list in sorted order, we also allow for passing in a custom IComparer<T> which, if provided, will be used to define the sort order:

public MySortedList(int capacity = 0, IComparer<T>? comparer = null)
{
    _list = new List<T>(capacity);
    _comparer = comparer;
}

Not shown are the class member variables for _list and _comparer, but from the constructor, we see that _list is our internal List<T> and _comparer is the IComparer<T> that we will use if it is provided.

For ease of use and to mirror List<T> we will also provide a constructor which takes an IEnumerable<T>:

public MySortedList(IEnumerable<T> initialValues, IComparer<T>? comparer = null) : this(comparer: comparer)
    => AddRange(initialValues);

With this constructor, we chain into our earlier constructor and then we pass the initialValues into our AddRange() function.

Adding Elements to Our Custom List Implementation

Our Add() method is where our new friend BinarySearch() really shines. As the name suggests, it searches through a sorted collection using a binary search strategy. Upon finding a matching element, it returns its index. When the element is not found, it returns a negative number that is the bitwise complement of the index of the next larger element. This means that by taking the complement, we get the insertion index for this item. Let’s take a look at our Add() method:

public void Add(T item)
{
    var index = _list.BinarySearch(item, _comparer);
    if (index < 0) index = ~index;

    _list.Insert(index, item);
}

On line #3 we see that the first thing we do, when adding, is to search for a matching item using BinarySearch(). The next step is to check whether the returned index is negative or not. As we mentioned earlier, in the case of a negative value (item not found), by taking the complement, we get our insertion index. The last step, line #6, is to perform the actual insertion. Since we allow duplicates, when there is a match we insert the new item at the index BinarySearch() returned, right next to its equal. When there is no match, we insert it at the complement of the result.

It will probably be clearer to understand this by walking through a simple example.

Using BinarySearch to Maintain Sort Order When Inserting

Let’s say we have the array of integers that we wish to insert into our custom MySortedList:

var data = new int[] {5, 1, 5, 3};

Now let’s loop through them, adding each one to our sorted list:

var sortedList = new MySortedList<int>();
foreach(var num in data) sortedList.Add(num);

The first time through the loop (5), the internal list is empty, so when we get to line #3 in the Add() method, BinarySearch() will return -1. Taking the complement, we get 0, and so we insert our element at index 0. And after the first iteration of the loop our list now looks like this: {5}

On our second iteration (1), BinarySearch() once again returns -1 as the item does not exist, and belongs at the beginning of the list (complement of -1 being 0). Now, our list looks like this: {1, 5}.

On our third iteration (5), BinarySearch() returns 1 as expected, since 5 already exists in our list. We insert the new item at the found index, and now have the following list: {1, 5, 5}.

Our fourth iteration (3), is where it gets a bit more interesting. This time BinarySearch() returns -2. Because the value is negative, we know the item was not found in the list. Taking the complement yields an index of 1, and so we insert the item at this location. After inserting, our final list looks like this: {1, 3, 5, 5}

Four rows. Each shows the value being added, the BinarySearch result (-1, -1, 1, -2), the insertion index (0, 0, 1, 1) and the list afterwards: {5}, {1, 5}, {1, 5, 5}, {1, 3, 5, 5}, with the inserted value highlighted.

Adding 5, 1, 5 and 3 to MySortedList: BinarySearch() gives the position, and the complement of a negative result is the insertion index.

This approach doesn’t guarantee insertion order among equal items. BinarySearch() can land on any of several equal elements. When we added “aa”, “bb”, “cc”, “dd”, “ee” and “x” with a comparer that compares only string length, the list came out as x, cc, ee, dd, bb, aa. The same goes for IndexOf(): a plain BinarySearch() might return any of the duplicates, so the version in our source code steps back to the first one, which is what IList<T> expects as long as the comparer returns 0 only for equal items.

Adding a Range of Elements

When it comes to adding a range of elements, we have two options. One option is to loop over the elements, calling our Add() method to insert each one in the proper location. The other option is to add them all to the end of the list and then sort it. We have chosen to implement the latter option due to the overall performance improvement. For completeness, let’s take a look at the method:

public void AddRange(IEnumerable<T> items)
{
    _list.AddRange(items);
    _list.Sort(_comparer);
}

If the collection being added is small, there is not much difference between the two options. As items grows, the gap grows fast.

We counted both approaches on random integers. Adding 100,000 numbers one at a time with Add() took about 1.52 million comparisons in BinarySearch(), which is fewer than the 1.85 million a single Sort() of the same numbers needed.

So the searching is cheap, and the time goes into shifting elements. Add(), on average, inserts elements into the middle of the list, and each Insert() moves every element after that index down by one. For 10,000 numbers that came to about 25 million element moves. For 100,000 it was 2.5 billion, roughly n²/4. Adding everything at once and sorting a single time replaces all of those moves with one O(n log n) sort.

Conclusion

We’ve explored several techniques for sorting a list in place. We looked at List.Sort() and its overloads, built comparers from an interface, from the Comparer<T> base class and from a lambda, saw why a comparer has to return 0 for two null values, and implemented our own always-sorted collection on top of BinarySearch().

One thing we haven’t covered is using LINQ to enumerate a collection in order without changing it. Our article on sorting with LINQ covers exactly that. And if you are still deciding which of the three comparison styles fits your own type, our IComparable vs IComparer article puts them side by side.

Tested with .NET 10.0.10 and xUnit 2.9.3.