StringComparer Classe

Définition

Représente une opération de comparaison de chaînes qui utilise des règles de tri spécifiques basées sur la casse et la culture ou des règles de comparaison ordinale.Represents a string comparison operation that uses specific case and culture-based or ordinal comparison rules.

public ref class StringComparer abstract : System::Collections::Generic::IComparer<System::String ^>, System::Collections::Generic::IEqualityComparer<System::String ^>, System::Collections::IComparer, System::Collections::IEqualityComparer
public abstract class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class StringComparer : System.Collections.Generic.IComparer<string>, System.Collections.Generic.IEqualityComparer<string>, System.Collections.IComparer, System.Collections.IEqualityComparer
type StringComparer = class
    interface IComparer<string>
    interface IEqualityComparer<string>
    interface IComparer
    interface IEqualityComparer
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Serializable>]
type StringComparer = class
    interface IComparer
    interface IEqualityComparer
    interface IComparer<string>
    interface IEqualityComparer<string>
Public MustInherit Class StringComparer
Implements IComparer, IComparer(Of String), IEqualityComparer, IEqualityComparer(Of String)
Héritage
StringComparer
Attributs
Implémente

Exemples

L’exemple suivant illustre les propriétés et la Create méthode de la StringComparer classe.The following example demonstrates the properties and the Create method of the StringComparer class. L’exemple montre comment différents StringComparer objets trient trois versions de la lettre latine I.The example illustrates how different StringComparer objects sort three versions of the Latin letter I.

// This example demonstrates members of the
// System::StringComparer class.

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Generic;
using namespace System::Globalization;
using namespace System::Threading;

void Display(List<String^>^ stringList, String^ title)
{
    Char firstChar;
    int codePoint;
    Console::WriteLine(title);
    for each (String^ s in stringList)
    {
        firstChar = s[0];
        codePoint = Convert::ToInt32(firstChar);
        Console::WriteLine("0x{0:x}", codePoint);
    }
    Console::WriteLine();
}

int main()
{
    // Create a list of string.
    List<String^>^ stringList = gcnew List<String^>();

    // Get the tr-TR (Turkish-Turkey) culture.
    CultureInfo^ turkishCulture = gcnew CultureInfo("tr-TR");

    // Get the culture that is associated with the current thread.
    CultureInfo^ currentCulture = Thread::CurrentThread->CurrentCulture;

    // Get the standard StringComparers.
    StringComparer^ invariant = StringComparer::InvariantCulture;
    StringComparer^ invariantIgnoreCase =
        StringComparer::InvariantCultureIgnoreCase;
    StringComparer^ current = StringComparer::CurrentCulture;
    StringComparer^ currentIgnoreCase =
        StringComparer::CurrentCultureIgnoreCase;
    StringComparer^ ordinal = StringComparer::Ordinal;
    StringComparer^ ordinalIgnoreCase = StringComparer::OrdinalIgnoreCase;

    // Create a StringComparer that uses the Turkish culture and ignores
    // case.
    StringComparer^ turkishIgnoreCase =
        StringComparer::Create(turkishCulture, true);

    // Define three strings consisting of different versions of the
    // letter I. LATIN CAPITAL LETTER I (U+0049)
    String^ capitalLetterI = "I";

    // LATIN SMALL LETTER I (U+0069)
    String^ smallLetterI = "i";

    // LATIN SMALL LETTER DOTLESS I (U+0131)
    String^ smallLetterDotlessI = L"\u0131";

    // Add the three strings to the list.
    stringList->Add(capitalLetterI);
    stringList->Add(smallLetterI);
    stringList->Add(smallLetterDotlessI);

    // Display the original list order.
    Display(stringList, "The original order of the list entries...");

    // Sort the list using the invariant culture.
    stringList->Sort(invariant);
    Display(stringList, "Invariant culture...");
    stringList->Sort(invariantIgnoreCase);
    Display(stringList, "Invariant culture, ignore case...");

    // Sort the list using the current culture.
    Console::WriteLine("The current culture is \"{0}\".",
        currentCulture->Name);
    stringList->Sort(current);
    Display(stringList, "Current culture...");
    stringList->Sort(currentIgnoreCase);
    Display(stringList, "Current culture, ignore case...");

    // Sort the list using the ordinal value of the character code points.
    stringList->Sort(ordinal);
    Display(stringList, "Ordinal...");
    stringList->Sort(ordinalIgnoreCase);
    Display(stringList, "Ordinal, ignore case...");

    // Sort the list using the Turkish culture, which treats LATIN SMALL
    // LETTER DOTLESS I differently than LATIN SMALL LETTER I.
    stringList->Sort(turkishIgnoreCase);
    Display(stringList, "Turkish culture, ignore case...");
}
/*
This code example produces the following results:

The original order of the list entries...
0x49
0x69
0x131

Invariant culture...
0x69
0x49
0x131

Invariant culture, ignore case...
0x49
0x69
0x131

The current culture is "en-US".
Current culture...
0x69
0x49
0x131

Current culture, ignore case...
0x49
0x69
0x131

Ordinal...
0x49
0x69
0x131

Ordinal, ignore case...
0x69
0x49
0x131

Turkish culture, ignore case...
0x131
0x49
0x69

*/
// This example demonstrates members of the 
// System.StringComparer class.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;

class Sample 
{
    public static void Main() 
    {
        // Create a list of string.
        List<string> list = new List<string>();

        // Get the tr-TR (Turkish-Turkey) culture.
        CultureInfo turkish = new CultureInfo("tr-TR");

        // Get the culture that is associated with the current thread.
        CultureInfo thisCulture = Thread.CurrentThread.CurrentCulture;

        // Get the standard StringComparers.
        StringComparer invCmp =   StringComparer.InvariantCulture;
        StringComparer invICCmp = StringComparer.InvariantCultureIgnoreCase;
        StringComparer currCmp = StringComparer.CurrentCulture;
        StringComparer currICCmp = StringComparer.CurrentCultureIgnoreCase;
        StringComparer ordCmp = StringComparer.Ordinal;
        StringComparer ordICCmp = StringComparer.OrdinalIgnoreCase;

        // Create a StringComparer that uses the Turkish culture and ignores case.
        StringComparer turkICComp = StringComparer.Create(turkish, true);

        // Define three strings consisting of different versions of the letter I.
        // LATIN CAPITAL LETTER I (U+0049)
        string capitalLetterI = "I";  

        // LATIN SMALL LETTER I (U+0069)
        string smallLetterI   = "i";

        // LATIN SMALL LETTER DOTLESS I (U+0131)
        string smallLetterDotlessI = "\u0131";

        // Add the three strings to the list.
        list.Add(capitalLetterI);
        list.Add(smallLetterI);
        list.Add(smallLetterDotlessI);

        // Display the original list order.
        Display(list, "The original order of the list entries...");

        // Sort the list using the invariant culture.
        list.Sort(invCmp);
        Display(list, "Invariant culture...");
        list.Sort(invICCmp);
        Display(list, "Invariant culture, ignore case...");

        // Sort the list using the current culture.
        Console.WriteLine("The current culture is \"{0}\".", thisCulture.Name);
        list.Sort(currCmp);
        Display(list, "Current culture...");
        list.Sort(currICCmp);
        Display(list, "Current culture, ignore case...");

        // Sort the list using the ordinal value of the character code points.
        list.Sort(ordCmp);
        Display(list, "Ordinal...");
        list.Sort(ordICCmp);
        Display(list, "Ordinal, ignore case...");

        // Sort the list using the Turkish culture, which treats LATIN SMALL LETTER 
        // DOTLESS I differently than LATIN SMALL LETTER I.
        list.Sort(turkICComp);
        Display(list, "Turkish culture, ignore case...");
    }

    public static void Display(List<string> lst, string title)
    {
        Char c;
        int  codePoint;
        Console.WriteLine(title);
        foreach (string s in lst)
        {
            c = s[0];
            codePoint = Convert.ToInt32(c);
            Console.WriteLine("0x{0:x}", codePoint); 
        }
        Console.WriteLine();
    }
}
/*
This code example produces the following results:

The original order of the list entries...
0x49
0x69
0x131

Invariant culture...
0x69
0x49
0x131

Invariant culture, ignore case...
0x49
0x69
0x131

The current culture is "en-US".
Current culture...
0x69
0x49
0x131

Current culture, ignore case...
0x49
0x69
0x131

Ordinal...
0x49
0x69
0x131

Ordinal, ignore case...
0x69
0x49
0x131

Turkish culture, ignore case...
0x131
0x49
0x69

*/
' This code example demonstrates members of the System.StringComparer class.

Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Threading

Class Sample
    
    Public Shared Sub Main() 
        ' Create a list of string.
        Dim list As New List(Of String) 
        
        ' Get the tr-TR (Turkish-Turkey) culture.
        Dim turkish As New CultureInfo("tr-TR")
        
        ' Get the culture that is associated with the current thread.
        Dim thisCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
        
        ' Get the standard StringComparers.
        Dim invCmp As StringComparer = StringComparer.InvariantCulture
        Dim invICCmp As StringComparer = StringComparer.InvariantCultureIgnoreCase
        Dim currCmp As StringComparer = StringComparer.CurrentCulture
        Dim currICCmp As StringComparer = StringComparer.CurrentCultureIgnoreCase
        Dim ordCmp As StringComparer = StringComparer.Ordinal
        Dim ordICCmp As StringComparer = StringComparer.OrdinalIgnoreCase
        
        ' Create a StringComparer that uses the Turkish culture and ignores case.
        Dim turkICComp As StringComparer = StringComparer.Create(turkish, True)
        
        ' Define three strings consisting of different versions of the letter I.
        ' LATIN CAPITAL LETTER I (U+0049)
        Dim capitalLetterI As String = "I"
        
        ' LATIN SMALL LETTER I (U+0069)
        Dim smallLetterI As String = "i"
        
        ' LATIN SMALL LETTER DOTLESS I (U+0131)
        Dim smallLetterDotlessI As String = "ı"
        
        ' Add the three strings to the list.
        list.Add(capitalLetterI)
        list.Add(smallLetterI)
        list.Add(smallLetterDotlessI)
        
        ' Display the original list order.
        Display(list, "The original order of the list entries...")
        
        ' Sort the list using the invariant culture.
        list.Sort(invCmp)
        Display(list, "Invariant culture...")
        list.Sort(invICCmp)
        Display(list, "Invariant culture, ignore case...")
        
        ' Sort the list using the current culture.
        Console.WriteLine("The current culture is ""{0}"".", thisCulture.Name)
        list.Sort(currCmp)
        Display(list, "Current culture...")
        list.Sort(currICCmp)
        Display(list, "Current culture, ignore case...")
        
        ' Sort the list using the ordinal value of the character code points.
        list.Sort(ordCmp)
        Display(list, "Ordinal...")
        list.Sort(ordICCmp)
        Display(list, "Ordinal, ignore case...")
        
        ' Sort the list using the Turkish culture, which treats LATIN SMALL LETTER 
        ' DOTLESS I differently than LATIN SMALL LETTER I.
        list.Sort(turkICComp)
        Display(list, "Turkish culture, ignore case...")
    
    End Sub
    
    Public Shared Sub Display(ByVal lst As List(Of String), ByVal title As String)
        Dim c As Char
        Dim s As String
        Dim codePoint As Integer

        Console.WriteLine(title)
        For Each s In lst
            c = s(0)
            codePoint = Convert.ToInt32(c)
            Console.WriteLine("0x{0:x}", codePoint)
        Next s
        Console.WriteLine()
    End Sub
End Class

'This code example produces the following results:
'
'The original order of the list entries...
'0x49
'0x69
'0x131
'
'Invariant culture...
'0x69
'0x49
'0x131
'
'Invariant culture, ignore case...
'0x49
'0x69
'0x131
'
'The current culture is "en-US".
'Current culture...
'0x69
'0x49
'0x131
'
'Current culture, ignore case...
'0x49
'0x69
'0x131
'
'Ordinal...
'0x49
'0x69
'0x131
'
'Ordinal, ignore case...
'0x69
'0x49
'0x131
'
'Turkish culture, ignore case...
'0x131
'0x49
'0x69
'

Remarques

Un objet dérivé de la StringComparer classe représente des opérations de comparaison basée sur chaîne, d’égalité et de code de hachage qui prennent en compte à la fois les règles de comparaison propres à la culture et à la casse.An object derived from the StringComparer class embodies string-based comparison, equality, and hash code operations that take into account both case and culture-specific comparison rules. Vous pouvez utiliser la StringComparer classe pour créer une comparaison spécifique au type pour trier les éléments d’une collection générique.You can use the StringComparer class to create a type-specific comparison to sort the elements in a generic collection. Les classes telles que Hashtable ,, Dictionary<TKey,TValue> SortedList et SortedList<TKey,TValue> utilisent la StringComparer classe à des fins de tri.Classes such as Hashtable, Dictionary<TKey,TValue>, SortedList, and SortedList<TKey,TValue> use the StringComparer class for sorting purposes.

Une opération de comparaison qui est représentée par la StringComparer classe est définie comme respectant la casse ou ne respecte pas la casse, et utilise des règles de comparaison de mots (dépendantes de la culture) ou ordinales (indépendantes de la culture).A comparison operation that is represented by the StringComparer class is defined to be either case-sensitive or case-insensitive, and use either word (culture-sensitive) or ordinal (culture-insensitive) comparison rules. Pour plus d’informations sur les règles de comparaison de mots et ordinales, consultez System.Globalization.CompareOptions .For more information about word and ordinal comparison rules, see System.Globalization.CompareOptions.

Notes

Vous pouvez télécharger les Sorting Weight Tables, un ensemble de fichiers texte qui contiennent des informations sur les poids des caractères utilisés dans les opérations de tri et de comparaison pour les systèmes d’exploitation Windows et la Default Unicode Collation Element Table, la version la plus récente de la table de pondération de tri pour Linux et macOS.You can download the Sorting Weight Tables, a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, and the Default Unicode Collation Element Table, the latest version of the sort weight table for Linux and macOS. La version spécifique de la table de pondération de tri sur Linux et macOS varie selon la version des bibliothèques International Components for Unicode installées sur le système.The specific version of the sort weight table on Linux and macOS depends on the version of the International Components for Unicode libraries installed on the system. Pour plus d’informations sur les versions ICU et les versions Unicode qu’elles implémentent, consultez Téléchargement d’ICU.For information on ICU versions and the Unicode versions that they implement, see Downloading ICU.

Propriétés implémentéesImplemented properties

Vous avez peut-être perdu à utiliser les StringComparer Propriétés de la classe en raison d’une contradiction apparente.You might be confused about how to use the StringComparer class properties because of a seeming contradiction. La StringComparer classe est déclarée abstract ( MustInherit en Visual Basic), ce qui signifie que ses membres peuvent être appelés uniquement sur un objet d’une classe dérivée de la StringComparer classe.The StringComparer class is declared abstract (MustInherit in Visual Basic), which means its members can be invoked only on an object of a class derived from the StringComparer class. La contradiction est que chaque propriété de la StringComparer classe est déclarée static ( Shared en Visual Basic), ce qui signifie que la propriété peut être appelée sans créer au préalable une classe dérivée.The contradiction is that each property of the StringComparer class is declared static (Shared in Visual Basic), which means the property can be invoked without first creating a derived class.

Vous pouvez appeler une StringComparer propriété directement, car chaque propriété retourne en fait une instance d’une classe anonyme qui est dérivée de la StringComparer classe.You can call a StringComparer property directly because each property actually returns an instance of an anonymous class that is derived from the StringComparer class. Par conséquent, le type de chaque valeur de propriété est StringComparer , qui est la classe de base de la classe anonyme, et non le type de la classe anonyme elle-même.Consequently, the type of each property value is StringComparer, which is the base class of the anonymous class, not the type of the anonymous class itself. Chaque StringComparer propriété de classe retourne un StringComparer objet qui prend en charge les règles de casse et de comparaison prédéfinies.Each StringComparer class property returns a StringComparer object that supports predefined case and comparison rules.

Constructeurs

StringComparer()

Initialise une nouvelle instance de la classe StringComparer.Initializes a new instance of the StringComparer class.

Propriétés

CurrentCulture

Obtient un objet StringComparer qui exécute une comparaison de chaînes respectant la casse à l'aide des règles de comparaison de mots de la culture actuelle.Gets a StringComparer object that performs a case-sensitive string comparison using the word comparison rules of the current culture.

CurrentCultureIgnoreCase

Obtient un objet StringComparer qui effectue des comparaisons de chaînes ne respectant pas la casse à l'aide des règles de comparaison de mots de la culture actuelle.Gets a StringComparer object that performs case-insensitive string comparisons using the word comparison rules of the current culture.

InvariantCulture

Obtient un objet StringComparer qui exécute une comparaison de chaînes respectant la casse à l'aide des règles de comparaison de mots de la culture indifférente.Gets a StringComparer object that performs a case-sensitive string comparison using the word comparison rules of the invariant culture.

InvariantCultureIgnoreCase

Obtient un objet StringComparer qui exécute une comparaison de chaînes ne respectant pas la casse à l'aide des règles de comparaison de mots de la culture indifférente.Gets a StringComparer object that performs a case-insensitive string comparison using the word comparison rules of the invariant culture.

Ordinal

Obtient un objet StringComparer qui effectue une comparaison de chaînes ordinale respectant la casse.Gets a StringComparer object that performs a case-sensitive ordinal string comparison.

OrdinalIgnoreCase

Obtient un objet StringComparer qui effectue une comparaison de chaînes ordinale ne respectant pas la casse.Gets a StringComparer object that performs a case-insensitive ordinal string comparison.

Méthodes

Compare(Object, Object)

En cas de substitution dans une classe dérivée, compare deux objets et retourne une indication de leur ordre de tri relatif.When overridden in a derived class, compares two objects and returns an indication of their relative sort order.

Compare(String, String)

En cas de substitution dans une classe dérivée, compare deux chaînes et retourne une indication de leur ordre de tri relatif.When overridden in a derived class, compares two strings and returns an indication of their relative sort order.

Create(CultureInfo, Boolean)

Crée un objet StringComparer qui compare des chaînes d'après les règles d'une culture spécifiée.Creates a StringComparer object that compares strings according to the rules of a specified culture.

Create(CultureInfo, CompareOptions)

Crée un objet StringComparer qui compare des chaînes d’après les règles d’une culture et d’options de chaîne spécifiées.Creates a StringComparer object that compares strings according to the rules of a specified culture and string options.

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.Determines whether the specified object is equal to the current object.

(Hérité de Object)
Equals(Object, Object)

En cas de substitution dans une classe dérivée, indique si deux objets sont égaux.When overridden in a derived class, indicates whether two objects are equal.

Equals(String, String)

En cas de substitution dans une classe dérivée, indique si deux chaînes sont égales.When overridden in a derived class, indicates whether two strings are equal.

FromComparison(StringComparison)

Convertit l’instance StringComparison spécifiée en une instance StringComparer.Converts the specified StringComparison instance to a StringComparer instance.

GetHashCode()

Fait office de fonction de hachage par défaut.Serves as the default hash function.

(Hérité de Object)
GetHashCode(Object)

En cas de substitution dans une classe dérivée, obtient le code de hachage pour l'objet spécifié.When overridden in a derived class, gets the hash code for the specified object.

GetHashCode(String)

En cas de substitution dans une classe dérivée, obtient le code de hachage pour la chaîne spécifiée.When overridden in a derived class, gets the hash code for the specified string.

GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Object actuel.Creates a shallow copy of the current Object.

(Hérité de Object)
ToString()

Retourne une chaîne qui représente l'objet actuel.Returns a string that represents the current object.

(Hérité de Object)

Implémentations d’interfaces explicites

IComparer.Compare(Object, Object)

Compare deux objets et retourne une valeur indiquant si le premier est inférieur, égal ou supérieur au second.Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.

IEqualityComparer.Equals(Object, Object)

Détermine si les objets spécifiés sont égaux.Determines whether the specified objects are equal.

IEqualityComparer.GetHashCode(Object)

Retourne un code de hachage pour l'objet spécifié.Returns a hash code for the specified object.

S’applique à

Voir aussi