Comparer<T> クラス

定義

IComparer<T> ジェネリック インターフェイスの実装のための基本クラスを提供します。

generic <typename T>
public ref class Comparer abstract : System::Collections::Generic::IComparer<T>, System::Collections::IComparer
public abstract class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer
[System.Serializable]
public abstract class Comparer<T> : System.Collections.Generic.IComparer<T>, System.Collections.IComparer
type Comparer<'T> = class
    interface IComparer<'T>
    interface IComparer
[<System.Serializable>]
type Comparer<'T> = class
    interface IComparer
    interface IComparer<'T>
Public MustInherit Class Comparer(Of T)
Implements IComparer, IComparer(Of T)

型パラメーター

T

比較するオブジェクトの型。

継承
Comparer<T>
属性
実装

次の例では、 BoxLengthFirstクラスからクラスを Comparer<T> 派生させます。 この比較子は、型の 2 つのオブジェクトを比較します Box。 最初に長さ、高さ、次に幅で並べ替えます。 このクラスはBox、2 つのBoxオブジェクト間のIComparable<T>既定の比較を制御するインターフェイスを実装します。 この既定の実装では、最初に高さ、長さ、次に幅で並べ替えます。 この例では、最初に比較子を使用してオブジェクトの一覧を並べ替え、次に既定の Box 比較子を BoxLengthFirst 使用して、2 つの比較の違いを示します。

using System;
using System.Collections;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        List<Box> Boxes = new List<Box>();
        Boxes.Add(new Box(4, 20, 14));
        Boxes.Add(new Box(12, 12, 12));
        Boxes.Add(new Box(8, 20, 10));
        Boxes.Add(new Box(6, 10, 2));
        Boxes.Add(new Box(2, 8, 4));
        Boxes.Add(new Box(2, 6, 8));
        Boxes.Add(new Box(4, 12, 20));
        Boxes.Add(new Box(18, 10, 4));
        Boxes.Add(new Box(24, 4, 18));
        Boxes.Add(new Box(10, 4, 16));
        Boxes.Add(new Box(10, 2, 10));
        Boxes.Add(new Box(6, 18, 2));
        Boxes.Add(new Box(8, 12, 4));
        Boxes.Add(new Box(12, 10, 8));
        Boxes.Add(new Box(14, 6, 6));
        Boxes.Add(new Box(16, 6, 16));
        Boxes.Add(new Box(2, 8, 12));
        Boxes.Add(new Box(4, 24, 8));
        Boxes.Add(new Box(8, 6, 20));
        Boxes.Add(new Box(18, 18, 12));

        // Sort by an Comparer<T> implementation that sorts
        // first by the length.
        Boxes.Sort(new BoxLengthFirst());

        Console.WriteLine("H - L - W");
        Console.WriteLine("==========");
        foreach (Box bx in Boxes)
        {
            Console.WriteLine("{0}\t{1}\t{2}",
                bx.Height.ToString(), bx.Length.ToString(),
                bx.Width.ToString());
        }

        Console.WriteLine();
        Console.WriteLine("H - L - W");
        Console.WriteLine("==========");

        // Get the default comparer that
        // sorts first by the height.
        Comparer<Box> defComp = Comparer<Box>.Default;

        // Calling Boxes.Sort() with no parameter
        // is the same as calling Boxs.Sort(defComp)
        // because they are both using the default comparer.
        Boxes.Sort();

        foreach (Box bx in Boxes)
        {
            Console.WriteLine("{0}\t{1}\t{2}",
                bx.Height.ToString(), bx.Length.ToString(),
                bx.Width.ToString());
        }


        // This explicit interface implementation
        // compares first by the length.
        // Returns -1 because the length of BoxA
        // is less than the length of BoxB.
        BoxLengthFirst LengthFirst = new BoxLengthFirst();

        Comparer<Box> bc = (Comparer<Box>) LengthFirst;

        Box BoxA = new Box(2, 6, 8);
        Box BoxB = new Box(10, 12, 14);
        int x = LengthFirst.Compare(BoxA, BoxB);
        Console.WriteLine();
        Console.WriteLine(x.ToString());
    }
}

public class BoxLengthFirst : Comparer<Box>
{
    // Compares by Length, Height, and Width.
    public override int Compare(Box x, Box y)
    {
        if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        else if (x.Height.CompareTo(y.Height) != 0)
        {
            return x.Height.CompareTo(y.Height);
        }
        else if (x.Width.CompareTo(y.Width) != 0)
        {
            return x.Width.CompareTo(y.Width);
        }
        else
        {
            return 0;
        }
    }
}

// This class is not demonstrated in the Main method
// and is provided only to show how to implement
// the interface. It is recommended to derive
// from Comparer<T> instead of implementing IComparer<T>.
public class BoxComp : IComparer<Box>
{
    // Compares by Height, Length, and Width.
    public int Compare(Box x, Box y)
    {
        if (x.Height.CompareTo(y.Height) != 0)
        {
            return x.Height.CompareTo(y.Height);
        }
        else if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        else if (x.Width.CompareTo(y.Width) != 0)
        {
            return x.Width.CompareTo(y.Width);
        }
        else
        {
            return 0;
        }
    }
}

public class Box : IComparable<Box>
{

    public Box(int h, int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }
    public int Height { get; private set; }
    public int Length { get; private set; }
    public int Width { get; private set; }

    public int CompareTo(Box other)
    {
        // Compares Height, Length, and Width.
        if (this.Height.CompareTo(other.Height) != 0)
        {
            return this.Height.CompareTo(other.Height);
        }
        else if (this.Length.CompareTo(other.Length) != 0)
        {
            return this.Length.CompareTo(other.Length);
        }
        else if (this.Width.CompareTo(other.Width) != 0)
        {
            return this.Width.CompareTo(other.Width);
        }
        else
        {
            return 0;
        }
    }
}
Imports System.Collections.Generic

Friend Class Program
    Shared Sub Main(ByVal args() As String)
        Dim Boxes As New List(Of Box)()
        Boxes.Add(New Box(4, 20, 14))
        Boxes.Add(New Box(12, 12, 12))
        Boxes.Add(New Box(8, 20, 10))
        Boxes.Add(New Box(6, 10, 2))
        Boxes.Add(New Box(2, 8, 4))
        Boxes.Add(New Box(2, 6, 8))
        Boxes.Add(New Box(4, 12, 20))
        Boxes.Add(New Box(18, 10, 4))
        Boxes.Add(New Box(24, 4, 18))
        Boxes.Add(New Box(10, 4, 16))
        Boxes.Add(New Box(10, 2, 10))
        Boxes.Add(New Box(6, 18, 2))
        Boxes.Add(New Box(8, 12, 4))
        Boxes.Add(New Box(12, 10, 8))
        Boxes.Add(New Box(14, 6, 6))
        Boxes.Add(New Box(16, 6, 16))
        Boxes.Add(New Box(2, 8, 12))
        Boxes.Add(New Box(4, 24, 8))
        Boxes.Add(New Box(8, 6, 20))
        Boxes.Add(New Box(18, 18, 12))

        ' Sort by an Comparer<T> implementation that sorts
        ' first by the length.
        Boxes.Sort(New BoxLengthFirst())

        Console.WriteLine("H - L - W")
        Console.WriteLine("==========")
        For Each bx As Box In Boxes
            Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}", _
                              bx.Height.ToString(), bx.Length.ToString(), _
                              bx.Width.ToString())
        Next bx

        Console.WriteLine()
        Console.WriteLine("H - L - W")
        Console.WriteLine("==========")

        ' Get the default comparer that 
        ' sorts first by the height.
        Dim defComp As Comparer(Of Box) = Comparer(Of Box).Default

        ' Calling Boxes.Sort() with no parameter
        ' is the same as calling Boxs.Sort(defComp)
        ' because they are both using the default comparer.
        Boxes.Sort()

        For Each bx As Box In Boxes
            Console.WriteLine("{0}" & vbTab & "{1}" & vbTab & "{2}", _
                              bx.Height.ToString(), _
                              bx.Length.ToString(), _
                              bx.Width.ToString())
        Next bx


        ' This explicit interface implementation
        ' compares first by the length.
        ' Returns -1 because the length of BoxA
        ' is less than the length of BoxB.
        Dim LengthFirst As New BoxLengthFirst()

        Dim bc As Comparer(Of Box) = CType(LengthFirst, Comparer(Of Box))

        Dim BoxA As New Box(2, 6, 8)
        Dim BoxB As New Box(10, 12, 14)
        Dim x As Integer = LengthFirst.Compare(BoxA, BoxB)
        Console.WriteLine()
        Console.WriteLine(x.ToString())



    End Sub

End Class

Public Class BoxLengthFirst
    Inherits Comparer(Of Box)
    ' Compares by Length, Height, and Width.
    Public Overrides Function Compare(ByVal x As Box, ByVal y As Box) As Integer
        If x.Length.CompareTo(y.Length) <> 0 Then
            Return x.Length.CompareTo(y.Length)
        ElseIf x.Height.CompareTo(y.Height) <> 0 Then
            Return x.Height.CompareTo(y.Height)
        ElseIf x.Width.CompareTo(y.Width) <> 0 Then
            Return x.Width.CompareTo(y.Width)
        Else
            Return 0
        End If
    End Function

End Class

' This class is not demonstrated in the Main method
' and is provided only to show how to implement
' the interface. It is recommended to derive
' from Comparer<T> instead of implementing IComparer<T>.
Public Class BoxComp
    Implements IComparer(Of Box)
    ' Compares by Height, Length, and Width.
    Public Function Compare(ByVal x As Box, ByVal y As Box) As Integer Implements _
                                                IComparer(Of Box).Compare
        If x.Height.CompareTo(y.Height) <> 0 Then
            Return x.Height.CompareTo(y.Height)
        ElseIf x.Length.CompareTo(y.Length) <> 0 Then
            Return x.Length.CompareTo(y.Length)
        ElseIf x.Width.CompareTo(y.Width) <> 0 Then
            Return x.Width.CompareTo(y.Width)
        Else
            Return 0
        End If
    End Function
End Class

Public Class Box
    Implements IComparable(Of Box)

    Public Sub New(ByVal h As Integer, ByVal l As Integer, ByVal w As Integer)
        Me.Height = h
        Me.Length = l
        Me.Width = w
    End Sub
    Private privateHeight As Integer
    Public Property Height() As Integer
        Get
            Return privateHeight
        End Get
        Private Set(ByVal value As Integer)
            privateHeight = value
        End Set
    End Property
    Private privateLength As Integer
    Public Property Length() As Integer
        Get
            Return privateLength
        End Get
        Private Set(ByVal value As Integer)
            privateLength = value
        End Set
    End Property
    Private privateWidth As Integer
    Public Property Width() As Integer
        Get
            Return privateWidth
        End Get
        Private Set(ByVal value As Integer)
            privateWidth = value
        End Set
    End Property

    Public Function CompareTo(ByVal other As Box) As Integer _
                        Implements IComparable(Of Box).CompareTo
        ' Compares Height, Length, and Width.
        If Me.Height.CompareTo(other.Height) <> 0 Then
            Return Me.Height.CompareTo(other.Height)
        ElseIf Me.Length.CompareTo(other.Length) <> 0 Then
            Return Me.Length.CompareTo(other.Length)
        ElseIf Me.Width.CompareTo(other.Width) <> 0 Then
            Return Me.Width.CompareTo(other.Width)
        Else
            Return 0
        End If
    End Function

End Class

注釈

このクラスから派生し、クラスやSortedDictionary<TKey,TValue>ジェネリック クラスなどのコレクション クラスで使用するインターフェイスのカスタム実装IComparer<T>SortedList<TKey,TValue>提供します。

クラスからの派生とインターフェイスの実装のComparer<T>System.IComparable違いは次のとおりです。

  • 既定で 2 つのオブジェクトを比較する方法を指定するには、クラスにインターフェイスを System.IComparable 実装します。 これにより、並べ替え操作で指定した既定の比較コードが使用されるようになります。

  • 既定の比較子の代わりに使用する比較子を定義するには、クラスから Comparer<T> 派生します。 その後、比較子をパラメーターとして受け取る並べ替え操作で、この比較子を使用できます。

プロパティによってDefault返されるオブジェクトは、ジェネリック インターフェイス (IComparable<T>C# では、 IComparable(Of T) Visual Basic) を使用System.IComparable<T>して 2 つのオブジェクトを比較します。 型 T がジェネリック インターフェイスを System.IComparable<T> 実装していない場合、 Default このプロパティはインターフェイスを使用する a Comparer<T>System.IComparable 返します。

注意 (実装者)

Compare(T, T) カルチャの感度と大文字と Equals(T, T) 小文字の区別の点で動作が異なる場合があります。

文字列比較の場合は、StringComparerComparerString<> よりもクラスをお勧めします。 クラスのプロパティは、 StringComparer カルチャと大文字と小文字の区別の異なる組み合わせで文字列比較を実行する定義済みのインスタンスを返します。 大文字と小文字の区別とカルチャの区別は、同じ StringComparer インスタンスのメンバー間で一貫しています。

カルチャ固有の比較の詳細については、名前空間とグローバリゼーションとローカリゼーションSystem.Globalization関するページを参照してください。

コンストラクター

Comparer<T>()

Comparer<T> クラスの新しいインスタンスを初期化します。

プロパティ

Default

汎用引数で指定された型に対して、既定の並べ替え順序比較子を返します。

メソッド

Compare(T, T)

派生クラスでオーバーライドされると、同じ型の 2 つのオブジェクトに対する比較を実行し、一方のオブジェクトが他方よりも小さいか、等しいか、大きいかを示す値を返します。

Create(Comparison<T>)

指定した比較を使用して比較子を作成します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

明示的なインターフェイスの実装

IComparer.Compare(Object, Object)

2 つのオブジェクトを比較して、一方が他方より小さいか、同じか、または大きいかを示す値を返します。

適用対象

こちらもご覧ください