StringComparer StringComparer StringComparer StringComparer Class

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
[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
    interface IEqualityComparer
    interface IComparer<string>
    interface IEqualityComparer<string>
Public MustInherit Class StringComparer
Implements IComparer, IComparer(Of String), IEqualityComparer, IEqualityComparer(Of String)
Héritage
StringComparerStringComparerStringComparerStringComparer
Attributs
Implémente

Exemples

L’exemple suivant illustre les propriétés et les Create méthode de la StringComparer classe.The following example demonstrates the properties and the Create method of the StringComparer class. L’exemple illustre comment les différents StringComparer objets tri trois versions de la Latin lettre 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
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 'Main
    
    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 'Display
End Class 'Sample '

'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

Objet dérivé de la StringComparer classe représente basé sur chaîne de comparaison, d’égalité et les opérations de code de hachage qui prennent en compte les règles de comparaison spécifiques à la culture et de 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 dans 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. Classes telles que Hashtable, Dictionary<TKey,TValue>, SortedList, et SortedList<TKey,TValue> utiliser le StringComparer classe pour le 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 à la casse ou non, et à utiliser des mots (dépendantes de la culture) ou des règles de comparaison (indépendantes de la culture) ordinale.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 word et les règles de comparaison ordinale, 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 serez peut-être ne sais pas comment utiliser le StringComparer propriétés de classe en raison d’une contradiction apparente.You might be confused about how to use the StringComparer class properties because of a seeming contradiction. Le StringComparer classe est déclarée abstract (MustInherit en Visual Basic), ce qui signifie que ses membres peut être appelée uniquement sur un objet d’une classe dérivée à partir 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 d’abord créer 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 un StringComparer propriété directement, car chaque propriété retourne 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 n’est pas la classe de base de la classe anonyme, le type de l’anonyme classe lui-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 classe de propriété 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() StringComparer() StringComparer() StringComparer()

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

Propriétés

CurrentCulture CurrentCulture CurrentCulture 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 CurrentCultureIgnoreCase CurrentCultureIgnoreCase 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 InvariantCulture InvariantCulture 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 InvariantCultureIgnoreCase InvariantCultureIgnoreCase 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 Ordinal Ordinal 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 OrdinalIgnoreCase OrdinalIgnoreCase 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) Compare(Object, Object) Compare(Object, Object) 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) Compare(String, String) Compare(String, String) 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) Create(CultureInfo, Boolean) Create(CultureInfo, Boolean) 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) Create(CultureInfo, CompareOptions) Create(CultureInfo, CompareOptions) Create(CultureInfo, CompareOptions)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Equals(Object, Object) Equals(Object, Object) Equals(Object, 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) Equals(String, String) Equals(String, String) 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) FromComparison(StringComparison) FromComparison(StringComparison) FromComparison(StringComparison)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetHashCode(Object) GetHashCode(Object) GetHashCode(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) GetHashCode(String) GetHashCode(String) 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() GetType() GetType() GetType()

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

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

Implémentations d’interfaces explicites

IComparer.Compare(Object, Object) IComparer.Compare(Object, Object) IComparer.Compare(Object, Object) IComparer.Compare(Object, Object)
IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object)
IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object)

S’applique à

Voir aussi