英語で読む

次の方法で共有


IComparable<T>.CompareTo(T) メソッド

定義

現在のインスタンスを同じ型の別のオブジェクトと比較し、現在のインスタンスの並べ替え順序での位置が、比較対象のオブジェクトと比べて前か、後か、または同じかを示す整数を返します。

C#
public int CompareTo(T other);
C#
public int CompareTo(T? other);

パラメーター

other
T

このインスタンスと比較するオブジェクト。

戻り値

比較対象オブジェクトの相対順序を示す値。 戻り値の意味は次のとおりです。

[値] 説明
0 より小さい値 このインスタンスの位置が、並べ替え順序において other よりも前です。
ゼロ 並べ替え順序における、このインスタンスと other の位置が同じです。
0 より大きい値 このインスタンスの位置が、並べ替え順序において other よりも後ろです。

次のコード例は、単純な Temperature オブジェクトの のIComparable<T>実装を示しています。 この例では、オブジェクト キーを SortedList<TKey,TValue> 持つ文字列のコレクションを Temperature 作成し、複数の温度と文字列のペアを順番にリストに追加します。 メソッドの Add 呼び出しでは、 SortedList<TKey,TValue> コレクションは 実装を IComparable<T> 使用してリスト エントリを並べ替え、温度を上げる順に表示されます。

C#
using System;
using System.Collections.Generic;

public class Temperature : IComparable<Temperature>
{
    // Implement the generic CompareTo method with the Temperature
    // class as the Type parameter.
    //
    public int CompareTo(Temperature other)
    {
        // If other is not a valid object reference, this instance is greater.
        if (other == null) return 1;

        // The temperature comparison depends on the comparison of
        // the underlying Double values.
        return m_value.CompareTo(other.m_value);
    }

    // Define the is greater than operator.
    public static bool operator >  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) > 0;
    }

    // Define the is less than operator.
    public static bool operator <  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) < 0;
    }

    // Define the is greater than or equal to operator.
    public static bool operator >=  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) >= 0;
    }

    // Define the is less than or equal to operator.
    public static bool operator <=  (Temperature operand1, Temperature operand2)
    {
       return operand1.CompareTo(operand2) <= 0;
    }

    // The underlying temperature value.
    protected double m_value = 0.0;

    public double Celsius
    {
        get
        {
            return m_value - 273.15;
        }
    }

    public double Kelvin
    {
        get
        {
            return m_value;
        }
        set
        {
            if (value < 0.0)
            {
                throw new ArgumentException("Temperature cannot be less than absolute zero.");
            }
            else
            {
                m_value = value;
            }
        }
    }

    public Temperature(double kelvins)
    {
        this.Kelvin = kelvins;
    }
}

public class Example
{
    public static void Main()
    {
        SortedList<Temperature, string> temps =
            new SortedList<Temperature, string>();

        // Add entries to the sorted list, out of order.
        temps.Add(new Temperature(2017.15), "Boiling point of Lead");
        temps.Add(new Temperature(0), "Absolute zero");
        temps.Add(new Temperature(273.15), "Freezing point of water");
        temps.Add(new Temperature(5100.15), "Boiling point of Carbon");
        temps.Add(new Temperature(373.15), "Boiling point of water");
        temps.Add(new Temperature(600.65), "Melting point of Lead");

        foreach( KeyValuePair<Temperature, string> kvp in temps )
        {
            Console.WriteLine("{0} is {1} degrees Celsius.", kvp.Value, kvp.Key.Celsius);
        }
    }
}
/* This example displays the following output:
      Absolute zero is -273.15 degrees Celsius.
      Freezing point of water is 0 degrees Celsius.
      Boiling point of water is 100 degrees Celsius.
      Melting point of Lead is 327.5 degrees Celsius.
      Boiling point of Lead is 1744 degrees Celsius.
      Boiling point of Carbon is 4827 degrees Celsius.
*/

注釈

CompareTo は、ジェネリック コレクション オブジェクトのメンバーを並べ替える厳密に型指定された比較メソッドを提供します。 このため、通常は開発者コードから直接呼び出されません。 代わりに、 や AddなどのList<T>.Sort()メソッドによって自動的に呼び出されます。

このメソッドは定義のみであり、特定のクラスまたは値の型で実装して効果を得る必要があります。 [戻り値] セクションで指定された比較の意味 ("前"、"と同じ位置で発生する"、および "フォローする" は、特定の実装によって異なります。

定義上、オブジェクトは より null大きく比較され、2 つの null 参照は互いに等しく比較されます。

注意 (実装者)

オブジェクト A、B、C の場合、次の条件を満たす必要があります。

A.CompareTo(A) は 0 を返すために必要です。

が 0 を返す場合 A.CompareTo(B) は、 B.CompareTo(A) 0 を返すために が必要です。

0 を返し、B.CompareTo(C)0 を返す場合A.CompareTo(B)は、A.CompareTo(C)0 を返す必要があります。

が 0 以外の値を返す場合 A.CompareTo(B) は、 B.CompareTo(A) 反対の符号の値を返す必要があります。

が 0 以外の値xを返し、 とB.CompareTo(C)同じ符号xの値yを返す場合A.CompareTo(B)は、 および A.CompareTo(C)y同じ符号xの値を返す必要があります。

注意 (呼び出し元)

クラスの CompareTo(T) インスタンスの順序を決定するには、 メソッドを使用します。

適用対象

製品 バージョン
.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, 10
.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.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください