Condividi tramite


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

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

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

Syntax

'Declaration
Public Sub Sort ( _
    comparison As Comparison(Of T) _
)
public void Sort(
    Comparison<T> comparison
)

Parameters

Exceptions

Exception Condition
ArgumentNullException

comparison is nulla null reference (Nothing in Visual Basic).

ArgumentException

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

Remarks

If comparison is provided, the elements of the List<T> are sorted using the method represented by the delegate.

If comparison is nulla null reference (Nothing in Visual Basic), an ArgumentNullException is thrown.

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.

Examples

The following code example demonstrates the Sort(Comparison<T>) method overload.

The code example defines an alternative comparison method for strings, named CompareDinosByLength. This method works as follows: First, the comparands are tested for nulla null reference (Nothing in Visual Basic), 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 also includes an empty string and a null reference. The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength method, and displayed again.

Imports System.Collections.Generic

Public Class Example

   Private Shared Function CompareDinosByLength( _
       ByVal x As String, ByVal y As String) As Integer

      If x Is Nothing Then
         If y Is Nothing Then
            ' If x is Nothing and y is Nothing, they're
            ' equal. 
            Return 0
         Else
            ' If x is Nothing and y is not Nothing, y
            ' is greater. 
            Return -1
         End If
      Else
         ' If x is not Nothing...
         '
         If y Is Nothing Then
            ' ...and y is Nothing, x is greater.
            Return 1
         Else
            ' ...and y is not Nothing, compare the 
            ' lengths of the two strings.
            '
            Dim retval As Integer = _
                x.Length.CompareTo(y.Length)

            If retval <> 0 Then
               ' 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)
            End If
         End If
      End If

   End Function

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Dim dinosaurs As New List(Of String)
      dinosaurs.Add("Pachycephalosaurus")
      dinosaurs.Add("Amargasaurus")
      dinosaurs.Add("")
      dinosaurs.Add(Nothing)
      dinosaurs.Add("Mamenchisaurus")
      dinosaurs.Add("Deinonychus")
      Display(outputBlock, dinosaurs)

      outputBlock.Text &= vbLf & "Sort with generic Comparison(Of String) delegate:" & vbCrLf
      dinosaurs.Sort(AddressOf CompareDinosByLength)
      Display(outputBlock, dinosaurs)

   End Sub

   Private Shared Sub Display(ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal lis As List(Of String))
      outputBlock.Text &= vbCrLf
      For Each s As String In lis
         If s Is Nothing Then
            outputBlock.Text &= "(Nothing)" & vbCrLf
         Else
            outputBlock.Text += String.Format("""{0}""", s) & vbCrLf
         End If
      Next
   End Sub
End Class

' This code example produces the following output:
'
'"Pachycephalosaurus"
'"Amargasaurus"
'""
'(Nothing)
'"Mamenchisaurus"
'"Deinonychus"
'
'Sort with generic Comparison(Of String) delegate:
'
'(Nothing)
'""
'"Deinonychus"
'"Amargasaurus"
'"Mamenchisaurus"
'"Pachycephalosaurus"
using System;
using System.Collections.Generic;

public class Example
{
   private static int CompareDinosByLength(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 static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      List<string> dinosaurs = new List<string>();
      dinosaurs.Add("Pachycephalosaurus");
      dinosaurs.Add("Amargasaurus");
      dinosaurs.Add("");
      dinosaurs.Add(null);
      dinosaurs.Add("Mamenchisaurus");
      dinosaurs.Add("Deinonychus");
      Display(outputBlock, dinosaurs);

      outputBlock.Text += "\nSort with generic Comparison<string> delegate:" + "\n";
      dinosaurs.Sort(CompareDinosByLength);
      Display(outputBlock, dinosaurs);

   }

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

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */

Version Information

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

Platforms

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