Partager via


Comparison<T> Délégué

Définition

Représente la méthode qui compare deux objets du même type.

generic <typename T>
public delegate int Comparison(T x, T y);
public delegate int Comparison<in T>(T x, T y);
public delegate int Comparison<T>(T x, T y);
type Comparison<'T> = delegate of 'T * 'T -> int
Public Delegate Function Comparison(Of In T)(x As T, y As T) As Integer 
Public Delegate Function Comparison(Of T)(x As T, y As T) As Integer 

Paramètres de type

T

Type des objets à comparer.

Ce paramètre de type est contravariant. Cela signifie que vous pouvez utiliser le type spécifié ou tout type moins dérivé. Pour plus d’informations sur la covariance et la contravariance, consultez Covariance et contravariance dans les génériques.

Paramètres

x
T

Premier objet à comparer.

y
T

Deuxième objet à comparer.

Valeur renvoyée

Int32

Entier signé qui indique les valeurs relatives de x et y, comme indiqué dans le tableau suivant.

Value Signification
Inférieure à 0 x est inférieur à y.
0 x est égal à y.
Supérieure à 0 x est supérieur à y.

Exemples

L’exemple de code suivant illustre l’utilisation du Comparison<T> délégué avec la Sort(Comparison<T>) surcharge de méthode.

L’exemple de code définit une autre méthode de comparaison pour les chaînes nommées CompareDinosByLength. Cette méthode fonctionne comme suit : Tout d’abord, les comparands sont testés pour null, et une référence null est traitée comme inférieure à une valeur non Null. Deuxièmement, les longueurs de chaîne sont comparées et la chaîne la plus longue est considérée comme supérieure. Troisièmement, si les longueurs sont égales, la comparaison de chaînes ordinaires est utilisée.

Une List<T> des chaînes est créée et remplie avec quatre chaînes, sans ordre particulier. La liste inclut également une chaîne vide et une référence null. La liste s’affiche, triée à l’aide d’un Comparison<T> délégué générique représentant la CompareDinosByLength méthode, puis affichée à nouveau.

using namespace System;
using namespace System::Collections::Generic;

int CompareDinosByLength(String^ x, String^ y)
{
    if (x == nullptr)
    {
        if (y == nullptr)
        {
            // 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 == nullptr)
            // ...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);
            }
        }
    }
};

void Display(List<String^>^ list)
{
    Console::WriteLine();
    for each(String^ s in list)
    {
        if (s == nullptr)
            Console::WriteLine("(null)");
        else
            Console::WriteLine("\"{0}\"", s);
    }
};

void main()
{
    List<String^>^ dinosaurs = gcnew List<String^>();
    dinosaurs->Add("Pachycephalosaurus");
    dinosaurs->Add("Amargasaurus");
    dinosaurs->Add("");
    dinosaurs->Add(nullptr);
    dinosaurs->Add("Mamenchisaurus");
    dinosaurs->Add("Deinonychus");
    Display(dinosaurs);

    Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
    dinosaurs->Sort(
        gcnew Comparison<String^>(CompareDinosByLength));
    Display(dinosaurs);

}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<String^> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
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"
 */
open System

let compareDinosByLength (x: string) (y: string) =
    match x with 
    | null when isNull y ->
        // If x is null and y is null, they're equal.
        0
    | null ->
        // If x is null and y is not null, y is greater.
        -1
    | _ when isNull y->
        // If x is not null and y is null, x is greater.
        1
    | _ ->
        // If x is not null and y is not null, compare the lengths of the two strings.
        let retval = x.Length.CompareTo y.Length

        if retval <> 0 then
            // If the strings are not of equal length, the longer string is greater.
            retval
        else
            // If the strings are of equal length, sort them with ordinary string comparison.
            x.CompareTo y

let display list =
    printfn ""
    for s in list do
        if isNull s then
            printfn "(null)"
        else
            printfn $"\"%s{s}\""


let dinosaurs = ResizeArray()
dinosaurs.Add "Pachycephalosaurus"
dinosaurs.Add "Amargasaurus"
dinosaurs.Add ""
dinosaurs.Add null
dinosaurs.Add "Mamenchisaurus"
dinosaurs.Add "Deinonychus"
display dinosaurs

printfn "\nSort with generic Comparison<string> delegate:"
dinosaurs.Sort compareDinosByLength
display dinosaurs


// This code example produces the following output:
//
// "Pachycephalosaurus"
// "Amargasaurus"
// ""
// (null)
// "Mamenchisaurus"
// "Deinonychus"
//
// Sort with generic Comparison<string> delegate:
//
// (null)
// ""
// "Deinonychus"
// "Amargasaurus"
// "Mamenchisaurus"
// "Pachycephalosaurus"
Imports System.Collections.Generic

Public Class Example

    Private Shared Function CompareDinosByLength( _
        ByVal x As String, ByVal y As String) As Integer

        If x Is Nothing Then
            If y Is Nothing Then 
                ' If x is Nothing and y is Nothing, they're
                ' equal. 
                Return 0
            Else
                ' If x is Nothing and y is not Nothing, y
                ' is greater. 
                Return -1
            End If
        Else
            ' If x is not Nothing...
            '
            If y Is Nothing Then
                ' ...and y is Nothing, x is greater.
                Return 1
            Else
                ' ...and y is not Nothing, compare the 
                ' lengths of the two strings.
                '
                Dim retval As Integer = _
                    x.Length.CompareTo(y.Length)

                If retval <> 0 Then 
                    ' 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)
                End If
            End If
        End If

    End Function

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)
        dinosaurs.Add("Pachycephalosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("")
        dinosaurs.Add(Nothing)
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")
        Display(dinosaurs)

        Console.WriteLine(vbLf & "Sort with generic Comparison(Of String) delegate:")
        dinosaurs.Sort(AddressOf CompareDinosByLength)
        Display(dinosaurs)

    End Sub

    Private Shared Sub Display(ByVal lis As List(Of String))
        Console.WriteLine()
        For Each s As String In lis
            If s Is Nothing Then
                Console.WriteLine("(Nothing)")
            Else
                Console.WriteLine("""{0}""", s)
            End If
        Next
    End Sub
End Class

' This code example produces the following output:
'
'"Pachycephalosaurus"
'"Amargasaurus"
'""
'(Nothing)
'"Mamenchisaurus"
'"Deinonychus"
'
'Sort with generic Comparison(Of String) delegate:
'
'(Nothing)
'""
'"Deinonychus"
'"Amargasaurus"
'"Mamenchisaurus"
'"Pachycephalosaurus"

L’exemple suivant utilise le Comparison<T> délégué pour trier les éléments d’une collection d’objets CityInfo . CityInfo est une classe définie par l’application qui contient des informations sur une ville et sa population. L’exemple définit trois méthodes, CompareByName, CompareByPopulationet CompareByNames, qui offrent trois façons différentes de classer les CityInfo objets. Chaque méthode est affectée à l’argument comparison de la Array.Sort<T>(T[], Comparison<T>) méthode.

using System;

public class CityInfo
{
   string cityName;
   string countryName;
   int pop2010;

   public CityInfo(string name, string country, int pop2010)
   {
      this.cityName = name;
      this.countryName = country;
      this.pop2010 = pop2010;
   }

   public string City
   { get { return this.cityName; } }

   public string Country
   { get { return this.countryName; } }

   public int Population
   { get { return this.pop2010; } }

   public static int CompareByName(CityInfo city1, CityInfo city2)
   {
      return String.Compare(city1.City, city2.City);
   }

   public static int CompareByPopulation(CityInfo city1, CityInfo city2)
   {
      return city1.Population.CompareTo(city2.Population);
   }

   public static int CompareByNames(CityInfo city1, CityInfo city2)
   {
      return String.Compare(city1.Country + city1.City, city2.Country + city2.City);
   }
}

public class Example
{
   public static void Main()
   {
      CityInfo NYC = new CityInfo("New York City", "United States of America", 8175133 );
      CityInfo Det = new CityInfo("Detroit", "United States of America", 713777);
      CityInfo Paris = new CityInfo("Paris", "France",  2193031);
      CityInfo[] cities = { NYC, Det, Paris };
      // Display ordered array.
      DisplayArray(cities);

      // Sort array by city name.
      Array.Sort(cities, CityInfo.CompareByName);
      DisplayArray(cities);

      // Sort array by population.
      Array.Sort(cities, CityInfo.CompareByPopulation);
      DisplayArray(cities);

      // Sort array by country + city name.
      Array.Sort(cities, CityInfo.CompareByNames);
      DisplayArray(cities);
   }

   private static void DisplayArray(CityInfo[] cities)
   {
      Console.WriteLine("{0,-20} {1,-25} {2,10}", "City", "Country", "Population");
      foreach (var city in cities)
         Console.WriteLine("{0,-20} {1,-25} {2,10:N0}", city.City,
                           city.Country, city.Population);

      Console.WriteLine();
   }
}
// The example displays the following output:
//     City                 Country                   Population
//     New York City        United States of America   8,175,133
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//     New York City        United States of America   8,175,133
//
//     City                 Country                   Population
//     Paris                France                     2,193,031
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133
open System

type CityInfo =
    { City: string
      Country: string
      Population: int }

    static member CompareByName city1 city2 =
        String.Compare(city1.City, city2.City)

    static member CompareByPopulation city1 city2 =
        city1.Population.CompareTo city2.Population 

    static member CompareByNames city1 city2 =
        String.Compare(city1.Country + city1.City, city2.Country + city2.City)

let display cities =
    printfn $"""{"City",-20} {"Country",-25} {"Population",10}"""
    for city in cities do
        printfn $"{city.City,-20} {city.Country,-25} {city.Population,10:N0}"
    printfn ""

let NYC = { City = "New York City"; Country = "United States of America"; Population = 8175133 }
let Det = { City = "Detroit"; Country = "United States of America"; Population = 713777 }
let Paris = { City = "Paris"; Country = "France"; Population = 2193031 }
let cities = [| NYC; Det; Paris |]
// Display ordered array.
display cities

// Sort array by city name.
Array.Sort(cities, CityInfo.CompareByName)
display cities

// Sort array by population.
Array.Sort(cities, CityInfo.CompareByPopulation);
display cities

// Sort array by country + city name.
Array.Sort(cities, CityInfo.CompareByNames);
display cities


// The example displays the following output:
//     City                 Country                   Population
//     New York City        United States of America   8,175,133
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//     New York City        United States of America   8,175,133
//
//     City                 Country                   Population
//     Paris                France                     2,193,031
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133
Public Class CityInfo
   Dim cityName As String
   Dim countryName As String
   Dim pop2010 As Integer
   
   Public Sub New(name As String, country As String, pop2010 As Integer)
      Me.cityName = name
      Me.countryName = country
      Me.pop2010 = pop2010
   End Sub
   
   Public ReadOnly Property City As String
      Get
         Return Me.cityName
      End Get
   End Property
   
   Public ReadOnly Property Country As String
      Get
         Return Me.countryName
      End Get
   End Property
   
   Public ReadOnly Property Population As Integer
      Get
         Return Me.pop2010
      End Get   
   End Property
   
   Public Shared Function CompareByName(city1 As CityInfo, city2 As CityInfo) As Integer
      Return String.Compare(city1.City, city2.City)
   End Function
   
   Public Shared Function CompareByPopulation(city1 As CityInfo, city2 As CityInfo) As Integer
      Return city1.Population.CompareTo(city2.Population)
   End Function
   
   Public Shared Function CompareByNames(city1 As CityInfo, city2 As CityInfo) As Integer
      Return String.Compare(city1.Country + city1.City, city2.Country + city2.City)
   End Function   
End Class

Module Example
   Public Sub Main()
      Dim NYC As New CityInfo("New York City", "United States of America", 8175133)
      Dim Det As New CityInfo("Detroit", "United States of America", 713777)
      Dim Paris As New CityInfo("Paris", "France", 2193031)
      Dim cities As CityInfo() = { NYC, Det, Paris }
      ' Display ordered array.
      DisplayArray(cities)
      
      ' Sort array by city name.
      Array.Sort(cities, AddressOf CityInfo.CompareByName)
      DisplayArray(cities)
      
      ' Sort array by population.
      Array.Sort(cities, AddressOf CityInfo.CompareByPopulation)
      DisplayArray(cities)
      
      ' Sort array by country + city name.
      Array.Sort(cities, AddressOf CityInfo.CompareByNames)
      DisplayArray(cities)
   End Sub
   
   Private Sub DisplayArray(cities() As CityInfo)
      Console.WriteLine("{0,-20} {1,-25} {2,10}", "City", "Country/Region", "Population")
      For Each city In cities
         Console.WriteLine("{0,-20} {1,-25} {2,10:N0}", city.City, city.Country, city.Population)
      Next
      Console.WriteLine()
   End Sub
End Module
' The example displays the following output:
'     City                 Country/Region            Population
'     New York City        United States of America   8,175,133
'     Detroit              United States of America     713,777
'     Paris                France                     2,193,031
'     
'     City                 Country/Region            Population
'     Detroit              United States of America     713,777
'     New York City        United States of America   8,175,133
'     Paris                France                     2,193,031
'     
'     City                 Country/Region            Population
'     Detroit              United States of America     713,777
'     Paris                France                     2,193,031
'     New York City        United States of America   8,175,133
'     
'     City                 Country/Region            Population
'     Paris                France                     2,193,031
'     Detroit              United States of America     713,777
'     New York City        United States of America   8,175,133

Remarques

Ce délégué est utilisé par la surcharge de méthode Sort<T>(T[], Comparison<T>) de la Array classe et la Sort(Comparison<T>) surcharge de méthode de la List<T> classe pour trier les éléments d’un tableau ou d’une liste.

Méthodes d’extension

GetMethodInfo(Delegate)

Obtient un objet qui représente la méthode représentée par le délégué spécifié.

S’applique à

Voir aussi