Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

List<T>.Sort Method (IComparer<T>)

Sorts the elements in the entire List<T> using the specified comparer.

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

public void Sort(
	IComparer<T> comparer
)

Parameters

comparer
Type: System.Collections.Generic.IComparer<T>
The IComparer<T> implementation to use when comparing elements, or null to use the default comparer Comparer<T>.Default.

ExceptionCondition
InvalidOperationException

comparer is null, and the default comparer Comparer<T>.Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T.

ArgumentException

The implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself.

If comparer is provided, the elements of the List<T> are sorted using the specified IComparer<T> implementation.

If comparer is null, the default comparer Comparer<T>.Default checks whether type T implements the IComparable<T> generic interface and uses that implementation, if available. If not, Comparer<T>.Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer<T>.Default throws an InvalidOperationException.

This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n ^ 2) operation.

The following code example demonstrates the Sort(IComparer<T>) method overload and the BinarySearch(T, IComparer<T>) method overload.

The code example defines an alternative comparer for strings named DinoCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. The comparer works as follows: First, the comparands are tested for null, and a null reference is treated as less than a non-null. Second, the string lengths are compared, and the longer string is deemed to be greater. Third, if the lengths are equal, ordinary string comparison is used.

A List<T> of strings is created and populated with four strings, in no particular order. The list is displayed, sorted using the alternate comparer, and displayed again.

The BinarySearch(T, IComparer<T>) method overload is then used to search for several strings that are not in the list, employing the alternate comparer. The Insert method is used to insert the strings. These two methods are located in the function named SearchAndInsert, along with code to take the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of the negative number returned by BinarySearch(T, IComparer<T>) and use it as an index for inserting the new string.


using System;
using System.Collections.Generic;

public class DinoComparer : IComparer<string>
{
   public int Compare(string x, string y)
   {
      if (x == null)
      {
         if (y == null)
         {
            // If x is null and y is null, they're
            // equal. 
            return 0;
         }
         else
         {
            // If x is null and y is not null, y
            // is greater. 
            return -1;
         }
      }
      else
      {
         // If x is not null...
         //
         if (y == null)
         // ...and y is null, x is greater.
         {
            return 1;
         }
         else
         {
            // ...and y is not null, compare the 
            // lengths of the two strings.
            //
            int retval = x.Length.CompareTo(y.Length);

            if (retval != 0)
            {
               // If the strings are not of equal length,
               // the longer string is greater.
               //
               return retval;
            }
            else
            {
               // If the strings are of equal length,
               // sort them with ordinary string comparison.
               //
               return x.CompareTo(y);
            }
         }
      }
   }
}

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      List<string> dinosaurs = new List<string>();
      dinosaurs.Add("Pachycephalosaurus");
      dinosaurs.Add("Amargasaurus");
      dinosaurs.Add("Mamenchisaurus");
      dinosaurs.Add("Deinonychus");
      Display(outputBlock, dinosaurs);

      DinoComparer dc = new DinoComparer();

      outputBlock.Text += "\nSort with alternate comparer:" + "\n";
      dinosaurs.Sort(dc);
      Display(outputBlock, dinosaurs);

      SearchAndInsert(outputBlock, dinosaurs, "Coelophysis", dc);
      Display(outputBlock, dinosaurs);

      SearchAndInsert(outputBlock, dinosaurs, "Oviraptor", dc);
      Display(outputBlock, dinosaurs);

      SearchAndInsert(outputBlock, dinosaurs, "Tyrannosaur", dc);
      Display(outputBlock, dinosaurs);

      SearchAndInsert(outputBlock, dinosaurs, null, dc);
      Display(outputBlock, dinosaurs);
   }

   private static void SearchAndInsert(System.Windows.Controls.TextBlock outputBlock, List<string> list,
       string insert, DinoComparer dc)
   {
      outputBlock.Text += String.Format("\nBinarySearch and Insert \"{0}\":", insert) + "\n";

      int index = list.BinarySearch(insert, dc);

      if (index < 0)
      {
         list.Insert(~index, insert);
      }
   }

   private static void Display(System.Windows.Controls.TextBlock outputBlock, List<string> list)
   {
      outputBlock.Text += "\n";
      foreach (string s in list)
      {
         outputBlock.Text += s + "\n";
      }
   }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort with alternate comparer:

Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Oviraptor":

Oviraptor
Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaur":

Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "":


Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus
 */


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft