在集合內比較和排序Comparisons and Sorts Within Collections

System.Collections 類別幾乎會在管理集合內的所有處理序中執行比較,包含搜尋要移除的項目,或傳回成對的索引鍵與值。The System.Collections classes perform comparisons in almost all the processes involved in managing collections, whether searching for the element to remove or returning the value of a key-and-value pair.

集合通常會利用等號比較子和 (或) 排序比較子。Collections typically utilize an equality comparer and/or an ordering comparer. 比較會使用兩個建構。Two constructs are used for comparisons.

檢查相等Checking for equality

例如, ContainsIndexOfLastIndexOfRemove 方法會為集合元素使用相等比較子。Methods such as Contains, IndexOf, LastIndexOf, and Remove use an equality comparer for the collection elements. 如果集合為泛型,則會根據下列方針,比較項目是否相等:If the collection is generic, than items are compared for equality according to the following guidelines:

此外,有些字典集合的建構函式多載可接受用來比較索引鍵是否相等的 IEqualityComparer<T> 實作。In addition, some constructor overloads for dictionary collections accept an IEqualityComparer<T> implementation, which is used to compare keys for equality. 如需範例,請參閱 Dictionary<TKey,TValue>.Dictionary<TKey,TValue>For an example, see the Dictionary<TKey,TValue>.Dictionary<TKey,TValue> constructor.

決定排序順序Determining sort order

例如,方法 BinarySearchSort 會為集合元素使用排序比較子。Methods such as BinarySearch and Sort use an ordering comparer for the collection elements. 比較可以在集合的元素之間進行,或在元素和指定的值之間進行。The comparisons can be between elements of the collection, or between an element and a specified value. 若為比較物件,會有 default comparerexplicit comparer的概念。For comparing objects, there is the concept of a default comparer and an explicit comparer.

預設比較子會依賴至少一個所比較的物件,實作 IComparable 介面。The default comparer relies on at least one of the objects being compared to implement the IComparable interface. 最好的作法是在所有用做為清單集合中的值或是用做為字典集合中索引鍵的類別上,實作 IComparableIt is a good practice to implement IComparable on all classes are used as values in a list collection or as keys in a dictionary collection. 若為泛型集合,會根據下列項目來決定相等比較:For a generic collection, equality comparison is determined according to the following:

若要提供明確比較,某些方法接受以 IComparer 實作做為參數。To provide explicit comparisons, some methods accept an IComparer implementation as a parameter. 例如, List<T>.Sort 方法接受 System.Collections.Generic.IComparer<T> 實作。For example, the List<T>.Sort method accepts an System.Collections.Generic.IComparer<T> implementation.

系統目前的文化特性設定,會影響集合內的比較和排序。The current culture setting of the system can affect the comparisons and sorts within a collection. 依預設, Collections 類別中的比較和排序會區分文化特性。By default, the comparisons and sorts in the Collections classes are culture-sensitive. 若要略過文化特性設定,並因而取得一致的比較和排序結果,請使用 InvariantCulture 搭配接受 CultureInfo的成員多載。To ignore the culture setting and therefore obtain consistent comparison and sorting results, use the InvariantCulture with member overloads that accept a CultureInfo. 如需詳細資訊,請參閱 Performing Culture-Insensitive String Operations in CollectionsPerforming Culture-Insensitive String Operations in ArraysFor more information, see Performing Culture-Insensitive String Operations in Collections and Performing Culture-Insensitive String Operations in Arrays.

相等和排序範例Equality and sort example

下列程式碼示範簡單商務物件上的 IEquatable<T>IComparable<T> 實作。The following code demonstrates an implementation of IEquatable<T> and IComparable<T> on a simple business object. 此外,當物件儲存在清單中且經過排序時,您會發現呼叫 Sort() 方法時,會為 Part 類型使用預設比較子,並使用匿名方法實作 Sort(Comparison<T>) 方法。In addition, when the object is stored in a list and sorted, you will see that calling the Sort() method results in the use of the default comparer for the Part type, and the Sort(Comparison<T>) method implemented by using an anonymous method.

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

         */

    }
}
Imports 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
    Implements IEquatable(Of Part)
    Implements IComparable(Of Part)
    Public Property PartName() As String
        Get
            Return m_PartName
        End Get
        Set(value As String)
            m_PartName = Value
        End Set
    End Property
    Private m_PartName As String

    Public Property PartId() As Integer
        Get
            Return m_PartId
        End Get
        Set(value As Integer)
            m_PartId = Value
        End Set
    End Property
    Private m_PartId As Integer

    Public Overrides Function ToString() As String
        Return "ID: " & PartId & "   Name: " & PartName
    End Function

    Public Overrides Function Equals(obj As Object) As Boolean
        If obj Is Nothing Then
            Return False
        End If
        Dim objAsPart As Part = TryCast(obj, Part)
        If objAsPart Is Nothing Then
            Return False
        Else
            Return Equals(objAsPart)
        End If
    End Function

    Public Function SortByNameAscending(name1 As String, name2 As String) As Integer

        Return name1.CompareTo(name2)
    End Function

    ' Default comparer for Part.
    Public Function CompareTo(comparePart As Part) As Integer _
            Implements IComparable(Of ListSortVB.Part).CompareTo
        ' A null value means that this object is greater.
        If comparePart Is Nothing Then
            Return 1
        Else

            Return Me.PartId.CompareTo(comparePart.PartId)
        End If
    End Function
    Public Overrides Function GetHashCode() As Integer
        Return PartId
    End Function
    Public Overloads Function Equals(other As Part) As Boolean Implements IEquatable(Of ListSortVB.Part).Equals
        If other Is Nothing Then
            Return False
        End If
        Return (Me.PartId.Equals(other.PartId))
    End Function
    ' Should also override == and != operators.

End Class
Public Class Example
    Public Shared Sub Main()
        ' Create a list of parts.
        Dim parts As New List(Of Part)()

        ' Add parts to the list.
        parts.Add(New Part() With { _
             .PartName = "regular seat", _
             .PartId = 1434 _
        })
        parts.Add(New Part() With { _
             .PartName = "crank arm", _
             .PartId = 1234 _
        })
        parts.Add(New Part() With { _
             .PartName = "shift lever", _
             .PartId = 1634 _
        })


        ' Name intentionally left null.
        parts.Add(New Part() With { _
             .PartId = 1334 _
        })
        parts.Add(New Part() With { _
             .PartName = "banana seat", _
             .PartId = 1444 _
        })
        parts.Add(New Part() With { _
             .PartName = "cassette", _
             .PartId = 1534 _
        })


        ' Write out the parts in the list. This will call the overridden 
        ' ToString method in the Part class.
        Console.WriteLine(vbLf & "Before sort:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next


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


        Console.WriteLine(vbLf & "After sort by part number:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

        ' This shows calling the Sort(Comparison(T) overload using 
        ' an anonymous delegate method. 
        ' This method treats null as the lesser of two values.
        parts.Sort(Function(x As Part, y As Part)
                             If x.PartName Is Nothing AndAlso y.PartName Is Nothing Then
                                 Return 0
                             ElseIf x.PartName Is Nothing Then
                                 Return -1
                             ElseIf y.PartName Is Nothing Then
                                 Return 1
                             Else
                                 Return x.PartName.CompareTo(y.PartName)
                             End If
                         End Function)
        

        Console.WriteLine(vbLf & "After sort by name:")
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next

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

    End Sub
End Class

另請參閱See also