List<T>.Sort 方法

定義

使用指定的或預設的 IComparer<T> 實作或提供的 Comparison<T> 委派來比較清單元素,以排序 List<T> 中的元素或元素的部分。

多載

Sort(Comparison<T>)

使用指定的 Comparison<T> 來排序在整個 List<T> 中的項目。

Sort(Int32, Int32, IComparer<T>)

使用指定的比較子對 List<T> 中某段範圍內的項目進行排序。

Sort()

使用預設的比較子來排序在整個 List<T> 中的項目。

Sort(IComparer<T>)

使用指定的比較子來排序在整個 List<T> 中的項目。

Sort(Comparison<T>)

來源:
List.cs
來源:
List.cs
來源:
List.cs

使用指定的 Comparison<T> 來排序在整個 List<T> 中的項目。

C#
public void Sort (Comparison<T> comparison);

參數

comparison
Comparison<T>

比較項目時所要使用的 Comparison<T>

例外狀況

comparisonnull

comparison 的實作在排序期間造成錯誤。 例如,在將項目與其本身比較時,comparison 可能不會傳回 0。

範例

下列程式代碼示範 Sort 簡單商務物件上的 和 Sort 方法多載。 Sort呼叫 方法會導致使用 Part 類型的預設比較子,並使用Sort匿名方法實作 方法。

C#
using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part> , IComparable<Part>
{
    public string PartName { get; set; }

    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: " + PartId + "   Name: " + PartName;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        Part objAsPart = obj as Part;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }
    public int SortByNameAscending(string name1, string name2)
    {

        return name1.CompareTo(name2);
    }

    // Default comparer for Part type.
    public int CompareTo(Part comparePart)
    {
          // A null value means that this object is greater.
        if (comparePart == null)
            return 1;

        else
            return this.PartId.CompareTo(comparePart.PartId);
    }
    public override int GetHashCode()
    {
        return PartId;
    }
    public bool Equals(Part other)
    {
        if (other == null) return false;
        return (this.PartId.Equals(other.PartId));
    }
    // Should also override == and != operators.
}
public class Example
{
    public static void Main()
    {
        // Create a list of parts.
        List<Part> parts = new List<Part>();

        // Add parts to the list.
        parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
        parts.Add(new Part() { PartName= "crank arm", PartId = 1234 });
        parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;
        // Name intentionally left null.
        parts.Add(new Part() {  PartId = 1334 });
        parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
        parts.Add(new Part() { PartName = "cassette", PartId = 1534 });

        // Write out the parts in the list. This will call the overridden
        // ToString method in the Part class.
        Console.WriteLine("\nBefore sort:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // Call Sort on the list. This will use the
        // default comparer, which is the Compare method
        // implemented on Part.
        parts.Sort();

        Console.WriteLine("\nAfter sort by part number:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // This shows calling the Sort(Comparison(T) overload using
        // an anonymous method for the Comparison delegate.
        // This method treats null as the lesser of two values.
        parts.Sort(delegate(Part x, Part y)
        {
            if (x.PartName == null && y.PartName == null) return 0;
            else if (x.PartName == null) return -1;
            else if (y.PartName == null) return 1;
            else return x.PartName.CompareTo(y.PartName);
        });

        Console.WriteLine("\nAfter sort by name:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        /*

            Before sort:
        ID: 1434   Name: regular seat
        ID: 1234   Name: crank arm
        ID: 1634   Name: shift lever
        ID: 1334   Name:
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette

        After sort by part number:
        ID: 1234   Name: crank arm
        ID: 1334   Name:
        ID: 1434   Name: regular seat
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette
        ID: 1634   Name: shift lever

        After sort by name:
        ID: 1334   Name:
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette
        ID: 1234   Name: crank arm
        ID: 1434   Name: regular seat
        ID: 1634   Name: shift lever

         */
    }
}

下列範例示範 Sort(Comparison<T>) 方法多載。

此範例會為名為 CompareDinosByLength的字串定義替代比較方法。 此方法的運作方式如下:首先,比較子會針對 null進行測試,並將 Null 參考視為小於非 Null。 其次,會比較字串長度,而且較長的字串會被視為更大。 第三,如果長度相等,則會使用一般字串比較。

建立字串的 , List<T> 並以四個字串填入,不依特定順序填入。 此清單也包含空字串和 Null 參考。 清單隨即顯示,使用 Comparison<T> 代表 方法的 CompareDinosByLength 泛型委派進行排序,然後再次顯示。

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"
 */

備註

如果 comparison 提供,則會使用委派所表示的方法來排序 的 List<T> 元素。

如果 comparisonnullArgumentNullException 則會擲回 。

此方法會使用 , Array.Sort其會套用簡介排序,如下所示:

  • 如果分割區大小小於或等於16個專案,則會使用插入排序演算法

  • 如果分割區數目超過 2 個 log n,其中 n 是輸入數位的範圍,則會使用 堆積演算法

  • 否則,它會使用 Quicksort 演算法。

此實作會執行不穩定的排序;也就是說,如果兩個元素相等,可能不會保留其順序。 相反地,穩定排序會保留相等的項目順序。

這個方法是 O (n log n) 作業,其中 nCount

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort(Int32, Int32, IComparer<T>)

來源:
List.cs
來源:
List.cs
來源:
List.cs

使用指定的比較子對 List<T> 中某段範圍內的項目進行排序。

C#
public void Sort (int index, int count, System.Collections.Generic.IComparer<T> comparer);
C#
public void Sort (int index, int count, System.Collections.Generic.IComparer<T>? comparer);

參數

index
Int32

要排序範圍內之以零為起始的起始索引。

count
Int32

要排序的範圍長度。

comparer
IComparer<T>

比較項目時要使用的 IComparer<T> 實作,或 null 表示使用預設比較子 Default

例外狀況

index 小於 0。

-或-

count 小於 0。

indexcount 未指定 List<T> 中的有效範圍。

-或-

comparer 的實作在排序期間造成錯誤。 例如,在將項目與其本身比較時,comparer 可能不會傳回 0。

comparernull,而且預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或 T 類型的 IComparable 介面。

範例

下列範例示範 Sort(Int32, Int32, IComparer<T>) 方法多載和 BinarySearch(Int32, Int32, T, IComparer<T>) 方法多載。

此範例會針對名為 DinoCompare 的字串定義替代比較子,它會 IComparer<string> 在 Visual Basic 中實作 Visual Basic 中的 (IComparer(Of String)IComparer<String^>) 泛型介面。 比較子的運作方式如下:首先,比較子會針對 null進行測試,並將 Null 參考視為小於非 Null。 其次,會比較字串長度,而且較長的字串會被視為更大。 第三,如果長度相等,則會使用一般字串比較。

會建立字串的 , List<T> 並填入五個動物恐龍和三個恐龍的名稱。 在這兩個群組的每一個群組中,名稱不是任何特定的排序順序。 隨即顯示清單、使用替代比較子排序 herbivores 的範圍,並再次顯示清單。

然後,方法 BinarySearch(Int32, Int32, T, IComparer<T>) 多載只會搜尋 「Brachiosaurus」 的 herbivores 範圍。 找不到字串,而位補碼 (C# 和 Visual C++ 中的 ~ 運算符,在 Visual Basic 中為 -1, Xor) 方法傳 BinarySearch(Int32, Int32, T, IComparer<T>) 回的負數,會當做插入新字元串的索引。

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
 */

備註

如果 comparer 提供,則會使用指定的IComparer<T>實作來排序 的List<T>元素。

如果 comparernull,則預設比較子 Comparer<T>.Default 會檢查類型 T 是否實作 IComparable<T> 泛型介面,並在可用時使用該實作。 如果沒有, Comparer<T>.Default 檢查類型 T 是否實作 IComparable 介面。 如果類型 T 未實作任一介面, Comparer<T>.Default 則會擲回 InvalidOperationException

此方法會使用 , Array.Sort其會套用簡介排序,如下所示:

  • 如果分割區大小小於或等於16個專案,則會使用插入排序演算法

  • 如果分割區數目超過 2 個 log n,其中 n 是輸入數位的範圍,則會使用 堆積演算法

  • 否則,它會使用 Quicksort 演算法。

此實作會執行不穩定的排序;也就是說,如果兩個元素相等,可能不會保留其順序。 相反地,穩定排序會保留相等的項目順序。

這個方法是 O (n log n) 作業,其中 nCount

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort()

來源:
List.cs
來源:
List.cs
來源:
List.cs

使用預設的比較子來排序在整個 List<T> 中的項目。

C#
public void Sort ();

例外狀況

預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或 T 類型的 IComparable 介面。

範例

下列範例會將一些名稱新增至 List<String> 物件、以未排序的順序顯示清單、呼叫 Sort 方法,然後顯示已排序的清單。

C#
String[] names = { "Samuel", "Dakota", "Koani", "Saya", "Vanya", "Jody",
                   "Yiska", "Yuma", "Jody", "Nikita" };
var nameList = new List<String>();
nameList.AddRange(names);
Console.WriteLine("List in unsorted order: ");
foreach (var name in nameList)
   Console.Write("   {0}", name);

Console.WriteLine(Environment.NewLine);

nameList.Sort();
Console.WriteLine("List in sorted order: ");
foreach (var name in nameList)
   Console.Write("   {0}", name);

Console.WriteLine();

// The example displays the following output:
//    List in unsorted order:
//       Samuel   Dakota   Koani   Saya   Vanya   Jody   Yiska   Yuma   Jody   Nikita
//
//    List in sorted order:
//       Dakota   Jody   Jody   Koani   Nikita   Samuel   Saya   Vanya   Yiska   Yuma

下列程式代碼示範 Sort() 簡單商務物件上的 和 Sort(Comparison<T>) 方法多載。 Sort()呼叫 方法會導致使用 Part 類型的預設比較子,並使用Sort(Comparison<T>)匿名方法實作 方法。

C#
using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part> , IComparable<Part>
{
    public string PartName { get; set; }

    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: " + PartId + "   Name: " + PartName;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        Part objAsPart = obj as Part;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }
    public int SortByNameAscending(string name1, string name2)
    {

        return name1.CompareTo(name2);
    }

    // Default comparer for Part type.
    public int CompareTo(Part comparePart)
    {
          // A null value means that this object is greater.
        if (comparePart == null)
            return 1;

        else
            return this.PartId.CompareTo(comparePart.PartId);
    }
    public override int GetHashCode()
    {
        return PartId;
    }
    public bool Equals(Part other)
    {
        if (other == null) return false;
        return (this.PartId.Equals(other.PartId));
    }
    // Should also override == and != operators.
}
public class Example
{
    public static void Main()
    {
        // Create a list of parts.
        List<Part> parts = new List<Part>();

        // Add parts to the list.
        parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
        parts.Add(new Part() { PartName= "crank arm", PartId = 1234 });
        parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;
        // Name intentionally left null.
        parts.Add(new Part() {  PartId = 1334 });
        parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
        parts.Add(new Part() { PartName = "cassette", PartId = 1534 });

        // Write out the parts in the list. This will call the overridden
        // ToString method in the Part class.
        Console.WriteLine("\nBefore sort:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // Call Sort on the list. This will use the
        // default comparer, which is the Compare method
        // implemented on Part.
        parts.Sort();

        Console.WriteLine("\nAfter sort by part number:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // This shows calling the Sort(Comparison(T) overload using
        // an anonymous method for the Comparison delegate.
        // This method treats null as the lesser of two values.
        parts.Sort(delegate(Part x, Part y)
        {
            if (x.PartName == null && y.PartName == null) return 0;
            else if (x.PartName == null) return -1;
            else if (y.PartName == null) return 1;
            else return x.PartName.CompareTo(y.PartName);
        });

        Console.WriteLine("\nAfter sort by name:");
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        /*

            Before sort:
        ID: 1434   Name: regular seat
        ID: 1234   Name: crank arm
        ID: 1634   Name: shift lever
        ID: 1334   Name:
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette

        After sort by part number:
        ID: 1234   Name: crank arm
        ID: 1334   Name:
        ID: 1434   Name: regular seat
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette
        ID: 1634   Name: shift lever

        After sort by name:
        ID: 1334   Name:
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette
        ID: 1234   Name: crank arm
        ID: 1434   Name: regular seat
        ID: 1634   Name: shift lever

         */
    }
}

下列範例示範 Sort() 方法多載和 BinarySearch(T) 方法多載。 建立字串的 , List<T> 並以四個字串填入,不依特定順序填入。 清單隨即顯示、排序,並再次顯示。

然後,方法 BinarySearch(T) 多載會用來搜尋不在清單中的兩個字串,並使用 Insert 方法插入它們。 方法的 BinarySearch 傳回值在每個案例中都是負數,因為字串不在清單中。 以位補碼 (C# 和 Visual C++ 中的 ~ 運算符, Xor 這個負數的 Visual Basic) -1 會產生清單中大於搜尋字串之第一個專案的索引,而且在此位置插入會保留排序順序。 第二個搜尋字串大於清單中的任何元素,因此插入位置位於清單的結尾。

C#
List<string> dinosaurs = new List<string>();

dinosaurs.Add("Pachycephalosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");

Console.WriteLine("Initial list:");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine("\nSort:");
dinosaurs.Sort();

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
int index = dinosaurs.BinarySearch("Coelophysis");
if (index < 0)
{
    dinosaurs.Insert(~index, "Coelophysis");
}

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}

Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
index = dinosaurs.BinarySearch("Tyrannosaurus");
if (index < 0)
{
    dinosaurs.Insert(~index, "Tyrannosaurus");
}

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
    Console.WriteLine(dinosaur);
}
/* This code example produces the following output:

Initial list:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort:

Amargasaurus
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaurus":

Amargasaurus
Coelophysis
Deinonychus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
*/

備註

這個方法會使用類型T的預設比較子Comparer<T>.Default來判斷清單項目的順序。 Comparer<T>.Default屬性會檢查類型T是否實作IComparable<T>泛型介面,並在可用時使用該實作。 如果沒有, Comparer<T>.Default 檢查類型 T 是否實作 IComparable 介面。 如果類型 T 未實作任一介面, Comparer<T>.Default 則會擲回 InvalidOperationException

這個方法會 Array.Sort 使用 方法,此方法會套用簡介排序,如下所示:

  • 如果分割區大小小於或等於16個專案,則會使用插入排序演算法。

  • 如果分割區數目超過 2 個 log n,其中 n 是輸入數位的範圍,則會使用堆積演算法。

  • 否則,它會使用 Quicksort 演算法。

此實作會執行不穩定的排序;也就是說,如果兩個元素相等,可能不會保留其順序。 相反地,穩定排序會保留相等的項目順序。

這個方法是 O (n log n) 作業,其中 nCount

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Sort(IComparer<T>)

來源:
List.cs
來源:
List.cs
來源:
List.cs

使用指定的比較子來排序在整個 List<T> 中的項目。

C#
public void Sort (System.Collections.Generic.IComparer<T> comparer);
C#
public void Sort (System.Collections.Generic.IComparer<T>? comparer);

參數

comparer
IComparer<T>

比較項目時要使用的 IComparer<T> 實作,或 null 表示使用預設比較子 Default

例外狀況

comparernull,而且預設比較子 Default 找不到 IComparable<T> 泛型介面的實作或 T 類型的 IComparable 介面。

comparer 的實作在排序期間造成錯誤。 例如,在將項目與其本身比較時,comparer 可能不會傳回 0。

範例

下列範例示範 Sort(IComparer<T>) 方法多載和 BinarySearch(T, IComparer<T>) 方法多載。

此範例會針對名為 DinoCompare 的字串定義替代比較子,它會 IComparer<string> 在 Visual Basic 中實作 Visual Basic 中的 (IComparer(Of String)IComparer<String^>) 泛型介面。 比較子的運作方式如下:首先,比較子會針對 null進行測試,並將 Null 參考視為小於非 Null。 其次,會比較字串長度,而且較長的字串會被視為更大。 第三,如果長度相等,則會使用一般字串比較。

建立字串的 , List<T> 並以四個字串填入,不依特定順序填入。 清單隨即顯示、使用替代比較子排序,並再次顯示。

然後,方法 BinarySearch(T, IComparer<T>) 多載會用來搜尋清單中沒有的數個字串,並採用替代比較子。 方法 Insert 可用來插入字串。 這兩種方法位於名為 SearchAndInsert的 函式中,以及程序代碼,以在 C# 和 Visual C++ 中取得 ~ 運算符的位補 (碼,在 Visual Basic 中為 -1, Xor) 傳回 BinarySearch(T, IComparer<T>) 的負數,並使用它做為插入新字元串的索引。

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("Amargasaurus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        Display(dinosaurs);

        DinoComparer dc = new DinoComparer();

        Console.WriteLine("\nSort with alternate comparer:");
        dinosaurs.Sort(dc);
        Display(dinosaurs);

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

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

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

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

    private static void SearchAndInsert(List<string> list,
        string insert, DinoComparer dc)
    {
        Console.WriteLine("\nBinarySearch and Insert \"{0}\":", insert);

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

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

    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
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
 */

備註

如果comparer提供 ,則會使用指定的IComparer<T>實作來排序 的List<T>元素。

如果 為 comparernull,則預設比較子 Comparer<T>.Default 會檢查類型 T 是否實作 IComparable<T> 泛型介面,並在可用時使用該實作。 如果沒有, Comparer<T>.Default 請檢查類型 T 是否實作 IComparable 介面。 如果類型 T 未實作任一介面, Comparer<T>.Default 則會擲回 InvalidOperationException

此方法會使用 Array.Sort 方法,其會套用簡介排序,如下所示:

  • 如果分割區大小小於或等於16個專案,則會使用插入排序演算法。

  • 如果分割區數目超過 2 個記錄 n,其中 n 是輸入數位的範圍,則會使用堆積演算法。

  • 否則,它會使用 Quicksort 演算法。

此實作會執行不穩定的排序;也就是說,如果兩個元素相等,則可能不會保留其順序。 相反地,穩定排序會保留相等的項目順序。

此方法是 o (n log n) 作業,其中 nCount

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0