Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 3.5
List(T) Class
List(T) Methods
Sort Method
 Sort Method (Comparison(T))
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Class Library
List<(Of <(T>)>)..::.Sort Method (Comparison<(Of <(T>)>))

Sorts the elements in the entire List<(Of <(T>)>) using the specified System..::.Comparison<(Of <(T>)>).

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic (Declaration)
Public Sub Sort ( _
    comparison As Comparison(Of T) _
)
Visual Basic (Usage)
Dim instance As List
Dim comparison As Comparison(Of T)

instance.Sort(comparison)
C#
public void Sort(
    Comparison<T> comparison
)
Visual C++
public:
void Sort(
    Comparison<T>^ comparison
)
JScript
public function Sort(
    comparison : Comparison<T>
)

Parameters

comparison
Type: System..::.Comparison<(Of <(T>)>)
The System..::.Comparison<(Of <(T>)>) to use when comparing elements.
ExceptionCondition
ArgumentNullException

comparison is nullNothingnullptra 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.

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

If comparison is nullNothingnullptra 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.

The following code example demonstrates the Sort(Comparison<(Of <(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 nullNothingnullptra 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<(Of <(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<(Of <(T>)>) generic delegate representing the CompareDinosByLength method, and displayed again.

Visual Basic
Imports System
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 Main()

        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(dinosaurs)

        Console.WriteLine(vbLf & "Sort with generic Comparison(Of String) delegate:")
        dinosaurs.Sort(AddressOf CompareDinosByLength)
        Display(dinosaurs)

    End Sub

    Private Shared Sub Display(ByVal lis As List(Of String))
        Console.WriteLine()
        For Each s As String In lis
            If s Is Nothing Then
                Console.WriteLine("(Nothing)")
            Else
                Console.WriteLine("""{0}""", s)
            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"
C#
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 Main()
    {
        List<string> dinosaurs = new List<string>();
        dinosaurs.Add("Pachycephalosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("");
        dinosaurs.Add(null);
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        Display(dinosaurs);

        Console.WriteLine("\nSort with generic Comparison<string> delegate:");
        dinosaurs.Sort(CompareDinosByLength);
        Display(dinosaurs);

    }

    private static void Display(List<string> list)
    {
        Console.WriteLine();
        foreach( string s in list )
        {
            if (s == null)
                Console.WriteLine("(null)");
            else
                Console.WriteLine("\"{0}\"", s);
        }
    }
}

/* This code example produces the following output:

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

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
Visual C++
using namespace System;
using namespace System::Collections::Generic;

int CompareDinosByLength(String^ x, String^ y)
{
    if (x == nullptr)
    {
        if (y == nullptr)
        {
            // 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 == nullptr)
            // ...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);
            }
        }
    }
};

void Display(List<String^>^ list)
{
    Console::WriteLine();
    for each(String^ s in list)
    {
        if (s == nullptr)
            Console::WriteLine("(null)");
        else
            Console::WriteLine("\"{0}\"", s);
    }
};

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();
    dinosaurs->Add("Pachycephalosaurus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("");
    dinosaurs->Add(nullptr);
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");
    Display(dinosaurs);

    Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
    dinosaurs->Sort(
        gcnew Comparison<String^>(CompareDinosByLength));
    Display(dinosaurs);

}

/* This code example produces the following output:

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

Sort with generic Comparison<String^> delegate:

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

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
So sorting will be true      TheLonelyWolf ... Thomas Lee   |   Edit   |   Show History

Mode this line

Before:

...

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);
}

...

After:

...

return x->CompareTo(y);

...

and you see

before:

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

after:

(null)
""

"Amargasaurus"
"Deinonychus"
"Mamenchisaurus"
"Pachycephalosaurus"

Anonymous Method Example      BryanLivingston   |   Edit   |   Show History
Here's the syntax if you want to use anonymous methods that are available in newer versions of C#.

style.SettingsInParameterOrder.Sort(

delegate(Setting x, Setting y) { return x.ParameterOrder.CompareTo(y.ParameterOrder); });
Lamda Expression Example      BryanLivingston   |   Edit   |   Show History
Better yet, here's a lamda expression version that does the same thing, also in C#:

style.SettingsInParameterOrder.Sort((x, y) => x.ParameterOrder.CompareTo(y.ParameterOrder));

Flag as ContentBug
Full Example with Lambda      Jelgab   |   Edit   |   Show History
class Table
{
public String Model { get; set; }
public Int32 TheWidth { get; set; }
public Int32 TheHeight { get; set; }
} //class Table

private void Demo01()
{
List<Table> DemoList01 = new List<Table>
{
new Table { Model = "Model 1", TheHeight = 5, TheWidth = 3 },
new Table { Model = "Model 2", TheHeight = 7, TheWidth = 2 },
new Table { Model = "Model 3", TheHeight = 2, TheWidth = 2 },
new Table { Model = "Model 4", TheHeight = 9, TheWidth = 8 },
new Table { Model = "Model 5", TheHeight = 6, TheWidth = 9 },
};

//Before sorting by area:
DemoList01.ForEach( CurrentTable => Console.WriteLine( "Table: {0}. Height: {1}, Width: {2}, Area: {3}", CurrentTable.Model, CurrentTable.TheHeight, CurrentTable.TheWidth, CurrentTable.TheHeight * CurrentTable.TheWidth ) );

Console.WriteLine( "".PadRight( 100, '_' ) ); //Just a visual separator

//Sort:
DemoList01.Sort( ( Table1, Table2 ) => { return ( Table1.TheHeight * Table1.TheWidth ).CompareTo( Table2.TheHeight * Table2.TheWidth ); } );

//After sorting by area:
DemoList01.ForEach( CurrentTable => Console.WriteLine( "Table: {0}. Height: {1}, Width: {2}, Area: {3}", CurrentTable.Model, CurrentTable.TheHeight, CurrentTable.TheWidth, CurrentTable.TheHeight * CurrentTable.TheWidth ) );
} //private void Demo01()
Flag as ContentBug
Full Example with Lambda      Jelgab   |   Edit   |   Show History
Flag as ContentBug
Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker