List.Sort メソッド (Int32, Int32, ジェネリック IComparer) (System.Collections.Generic)

ビューの切り替え:
スクリプトなし
.NET Framework クラス ライブラリ
List.Sort メソッド (Int32, Int32, ジェネリック IComparer)

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

指定した比較演算子を使用して、List 内の要素の範囲内の要素を並べ替えます。

名前空間: System.Collections.Generic
アセンブリ: mscorlib (mscorlib.dll 内)

構文

Visual Basic (宣言)
Public Sub Sort ( _
	index As Integer, _
	count As Integer, _
	comparer As IComparer(Of T) _
)
Visual Basic (使用法)
Dim instance As List(Of T)
Dim index As Integer
Dim count As Integer
Dim comparer As IComparer(Of T)

instance.Sort(index, count, comparer)
C#
public void Sort (
	int index,
	int count,
	IComparer<T> comparer
)
C++
public:
void Sort (
	int index, 
	int count, 
	IComparer<T>^ comparer
)
J#
public void Sort (
	int index, 
	int count, 
	IComparer<T> comparer
)
JScript
public function Sort (
	index : int, 
	count : int, 
	comparer : IComparer<T>
)

パラメータ

index

並べ替える範囲の開始位置を示す 0 から始まるインデックス。

count

並べ替える範囲の長さ。

comparer

要素を比較する場合に使用する IComparer 実装。または、既定の比較演算子 Comparer.Default を使用する場合は null 参照 (Visual Basic では Nothing)。

例外

例外の種類 条件

ArgumentOutOfRangeException

index が 0 未満です。

または

count が 0 未満です。

ArgumentException

index および countList 内の有効な範囲を指定していません。

または

comparer の実装によって並べ替え中にエラーが発生しました。たとえば、comparer は項目をその項目自身と比較する場合に 0 を返さない可能性があります。

InvalidOperationException

comparer が null 参照 (Visual Basic では Nothing) です。また、既定の比較演算子 Comparer.Default は、IComparable ジェネリック インターフェイスの実装、または型 TIComparable インターフェイスの実装を見つけることができません。

解説

comparer が提供されている場合、List の要素は、指定した IComparer の実装を使用して並べ替えられます。

comparer が null 参照 (Visual Basic では Nothing) の場合、既定の比較演算子 Comparer.Default は、型 TIComparable ジェネリック インターフェイスを実装しているかどうかをチェックし、使用できる場合は、その実装を使用します。そうでない場合、Comparer.Default は、型 TIComparable インターフェイスを実装しているかどうかをチェックします。型 T がいずれのインターフェイスも実装しない場合、Comparer.DefaultInvalidOperationException をスローします。

このメソッドは、QuickSort アルゴリズムを使用する System.Array.Sort を使用します。この実装では不安定な並べ替えを実行します。つまり、2 つの要素が等しかった場合、これらの順序は保持されない可能性があります。一方、安定した並べ替えでは、等しい要素の順序が保持されます。

平均して、このメソッドは O(n log n) 操作です。ここで、nCount です。最悪の場合は O(n ^ 2) 操作です。

使用例

Sort(Int32,Int32,ジェネリック IComparer) メソッドのオーバーロードと BinarySearch(Int32,Int32,T,ジェネリック IComparer) メソッドのオーバーロードを使用したコード例を次に示します。

コード例では、DinoCompare という名前の文字列に対して、IComparer<string> (Visual Basic では IComparer(Of String)、Visual C++ では IComparer<String^>) ジェネリック インターフェイスを実装する代替の比較演算子を定義します。この比較演算子は次のように動作します。最初に、比較対象値が null 参照 (Visual Basic では Nothing) であるかがテストされ、null 参照は null 以外の値よりも小さなものとして扱われます。2 番目に、文字列長が比較され、より長い文字列は、より大きなものと判断されます。3 番目に、長さが等しい場合は、通常の文字列比較が使用されます。

文字列の List が作成され、5 つの草食性恐竜の名前と 3 つの肉食性恐竜の名前が設定されます。2 つのそれぞれのグループで、名前は特定の並べ替え順序にはなっていません。リストが表示されます。代替の比較演算子を使用して草食性恐竜の範囲がソートされ、リストが再表示されます。

次に BinarySearch(Int32,Int32,T,ジェネリック IComparer) メソッドのオーバーロードを使用して、草食性恐竜の範囲だけを対象に "Brachiosaurus" を検索します。その文字列は見つからず、BinarySearch(Int32,Int32,T,ジェネリック IComparer) メソッドで返される負の数のビットごとの補数 (C# と Visual C++ では ~ 演算子、Visual Basic では -1 の Xor) は、新しい文字列を挿入するためのインデックスとして使用されます。

Visual Basic
Imports System
Imports System.Collections.Generic

Public Class DinoComparer
    Implements IComparer(Of String)

    Public Function Compare(ByVal x As String, _
        ByVal y As String) As Integer _
        Implements IComparer(Of String).Compare

        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
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)

        dinosaurs.Add("Pachycephalosaurus")
        dinosaurs.Add("Parasauralophus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Galimimus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        dinosaurs.Add("Oviraptor")
        dinosaurs.Add("Tyrannosaurus")

        Dim herbivores As Integer = 5
        Display(dinosaurs)

        Dim dc As New DinoComparer

        Console.WriteLine(vbLf & _
            "Sort a range with the alternate comparer:")
        dinosaurs.Sort(0, herbivores, dc)
        Display(dinosaurs)

        Console.WriteLine(vbLf & _
            "BinarySearch a range and Insert ""{0}"":", _
            "Brachiosaurus")

        Dim index As Integer = _
            dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc)

        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Brachiosaurus")
            herbivores += 1
        End If

        Display(dinosaurs)

    End Sub

    Private Shared Sub Display(ByVal lis As List(Of String))
        Console.WriteLine()
        For Each s As String In lis
            Console.WriteLine(s)
        Next
    End Sub
End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Parasauralophus
'Amargasaurus
'Galimimus
'Mamenchisaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'Sort a range with the alternate comparer:
'
'Galimimus
'Amargasaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus
'
'BinarySearch a range and Insert "Brachiosaurus":
'
'Galimimus
'Amargasaurus
'Brachiosaurus
'Mamenchisaurus
'Parasauralophus
'Pachycephalosaurus
'Deinonychus
'Oviraptor
'Tyrannosaurus

C#
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 Main()
    {
        List<string> dinosaurs = new List<string>();

        dinosaurs.Add("Pachycephalosaurus");
        dinosaurs.Add("Parasauralophus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Galimimus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Oviraptor");
        dinosaurs.Add("Tyrannosaurus");

        int herbivores = 5;
        Display(dinosaurs);

        DinoComparer dc = new DinoComparer();

        Console.WriteLine("\nSort a range with the alternate comparer:");
        dinosaurs.Sort(0, herbivores, dc);
        Display(dinosaurs);

        Console.WriteLine("\nBinarySearch a range and Insert \"{0}\":",
            "Brachiosaurus");

        int index = dinosaurs.BinarySearch(0, herbivores, "Brachiosaurus", dc);

        if (index < 0)
        {
            dinosaurs.Insert(~index, "Brachiosaurus");
            herbivores++;
        }

        Display(dinosaurs);
    }

    private static void Display(List<string> list)
    {
        Console.WriteLine();
        foreach( string s in list )
        {
            Console.WriteLine(s);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus

Sort a range with the alternate comparer:

Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus

BinarySearch a range and Insert "Brachiosaurus":

Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
 */

C++
using namespace System;
using namespace System::Collections::Generic;

public ref class DinoComparer: IComparer<String^>
{
public:
    virtual int Compare(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)
    {
        Console::WriteLine(s);
    }
};

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();

    dinosaurs->Add("Pachycephalosaurus");
    dinosaurs->Add("Parasauralophus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("Galimimus");
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");
    dinosaurs->Add("Oviraptor");
    dinosaurs->Add("Tyrannosaurus");

    int herbivores = 5;
    Display(dinosaurs);

    DinoComparer^ dc = gcnew DinoComparer();

    Console::WriteLine("\nSort a range with the alternate comparer:");
    dinosaurs->Sort(0, herbivores, dc);
    Display(dinosaurs);

    Console::WriteLine("\nBinarySearch a range and Insert \"{0}\":",
            "Brachiosaurus");

    int index = dinosaurs->BinarySearch(0, herbivores, "Brachiosaurus", dc);

    if (index < 0)
    {
        dinosaurs->Insert(~index, "Brachiosaurus");
        herbivores++;
    }

    Display(dinosaurs);
}

/* This code example produces the following output:

Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus

Sort a range with the alternate comparer:

Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus

BinarySearch a range and Insert "Brachiosaurus":

Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
 */

プラットフォーム

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。

バージョン情報

.NET Framework

サポート対象 : 2.0

.NET Compact Framework

サポート対象 : 2.0
参照