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

Source:
List.cs
Source:
List.cs
Source:
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。 其次,比较字符串长度,较长的字符串被认为更大。 第三,如果长度相等,则使用普通字符串比较。

字符串 List<T> 的 创建并填充了四个字符串,没有特定顺序。 该列表还包括一个空字符串和一个 null 引用。 显示列表,使用表示 CompareDinosByLength 方法的Comparison<T>泛型委托进行排序,然后再次显示。

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 个对数 n,其中 n 是输入数组的范围,则它使用 堆排序 算法。

  • 否则,它使用快速排序算法。

此实现执行不稳定排序;也就是说,如果两个元素相等,则可能不会保留其顺序。 相比之下,稳定排序会保留相等元素的顺序。

此方法是 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>)

Source:
List.cs
Source:
List.cs
Source:
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> 实现,若要使用默认比较器 Default,则为 null

例外

index 小于 0。

count 小于 0。

indexcount 未在 List<T> 中指定有效范围。

- 或 -

comparer 的实现导致排序时出现错误。 例如,将某个项与其自身比较时,comparer 可能不返回 0。

comparernull,且默认比较器 Default 找不到 IComparable<T> 泛型接口或类型为 TIComparable 接口的实现。

示例

以下示例演示方法 Sort(Int32, Int32, IComparer<T>) 重载和 BinarySearch(Int32, Int32, T, IComparer<T>) 方法重载。

该示例为名为 DinoCompare 的字符串定义了一个替代比较器,该比较器在 Visual CIComparer<String^>++ 中实现 IComparer<string> visual C++ 中的 (IComparer(Of String)) 泛型接口。 比较器的工作方式如下:首先,对 比较值进行测试 null,空引用被视为小于非 null。 其次,比较字符串长度,较长的字符串被认为更大。 第三,如果长度相等,则使用普通字符串比较。

一个 List<T> 字符串被创建和填充五个食草恐龙和三个食肉恐龙的名称。 在两个组中,名称不采用任何特定的排序顺序。 显示列表,使用备用比较器对食草动物的范围进行排序,并再次显示该列表。

然后,该方法 BinarySearch(Int32, Int32, T, IComparer<T>) 重载用于仅搜索食草动物的范围以查找“Brachiosaurus”。 找不到字符串,并且按位补 (C# 中的 ~ 运算符和 Visual C++ Xor 中的 -1,方法返回 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不实现任一InvalidOperationException接口,Comparer<T>.Default将引发 。

此方法使用 Array.Sort,它应用自省排序,如下所示:

  • 如果分区大小小于或等于 16 个元素,则它使用插入排序算法

  • 如果分区数超过 2 个对数 n,其中 n 是输入数组的范围,则它使用 堆排序 算法。

  • 否则,它使用快速排序算法。

此实现执行不稳定排序;也就是说,如果两个元素相等,则可能不会保留其顺序。 相比之下,稳定排序会保留相等元素的顺序。

此方法是 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()

Source:
List.cs
Source:
List.cs
Source:
List.cs

使用默认比较器对整个 List<T> 中的元素进行排序。

C#
public void Sort ();

例外

此默认比较器 Default 无法找到 IComparable<T> 泛型接口或类型为 TIComparable 接口的实现。

示例

以下示例向 对象添加一 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不实现任一InvalidOperationException接口,Comparer<T>.Default将引发 。

此方法使用 Array.Sort 方法,该方法应用自省排序,如下所示:

  • 如果分区大小小于或等于 16 个元素,则它使用插入排序算法。

  • 如果分区数超过 2 个对数 n,其中 n 是输入数组的范围,则它使用堆排序算法。

  • 否则,它使用快速排序算法。

此实现执行不稳定排序;也就是说,如果两个元素相等,则可能不会保留其顺序。 相比之下,稳定排序会保留相等元素的顺序。

此方法是 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>)

Source:
List.cs
Source:
List.cs
Source:
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> 实现,若要使用默认比较器 Default,则为 null

例外

comparernull,且默认比较器 Default 找不到 IComparable<T> 泛型接口或类型为 TIComparable 接口的实现。

comparer 的实现导致排序时出现错误。 例如,将某个项与其自身比较时,comparer 可能不返回 0。

示例

以下示例演示方法 Sort(IComparer<T>) 重载和 BinarySearch(T, IComparer<T>) 方法重载。

该示例为名为 DinoCompare 的字符串定义了一个替代比较器,该比较器在 Visual CIComparer<String^>++ 中实现 IComparer<string> visual C++ 中的 (IComparer(Of String)) 泛型接口。 比较器的工作方式如下:首先,对 比较值进行测试 null,空引用被视为小于非 null。 其次,比较字符串长度,较长的字符串被认为更大。 第三,如果长度相等,则使用普通字符串比较。

字符串 List<T> 的 创建并填充了四个字符串,没有特定顺序。 列表随即显示,使用备用比较器进行排序,然后再次显示。

然后,使用 BinarySearch(T, IComparer<T>) 方法重载来搜索不在列表中的多个字符串,并使用备用比较器。 方法 Insert 用于插入字符串。 这两种方法位于名为 SearchAndInsert的函数中,以及采用 C# 和 Visual C++ 中 ~ 运算符 (位补码的代码, Xor 在 Visual Basic 中获取 -1) 返回 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不实现任一InvalidOperationException接口,Comparer<T>.Default将引发 。

此方法使用 Array.Sort 方法,该方法应用自省排序,如下所示:

  • 如果分区大小小于或等于 16 个元素,则它使用插入排序算法。

  • 如果分区数超过 2 个对数 n,其中 n 是输入数组的范围,则它使用堆排序算法。

  • 否则,它使用快速排序算法。

此实现执行不稳定排序;也就是说,如果两个元素相等,则可能不会保留其顺序。 相比之下,稳定排序会保留相等元素的顺序。

此方法是 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