StringComparer StringComparer StringComparer StringComparer Class

Definición

Representa una operación de comparación de cadenas que utiliza reglas específicas basadas en la referencia cultural y el uso de mayúsculas y minúsculas o reglas específicas de comparación de ordinales.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)
Herencia
StringComparerStringComparerStringComparerStringComparer
Atributos
Implementaciones

Ejemplos

En el ejemplo siguiente se muestran las propiedades Create y el método StringComparer de la clase.The following example demonstrates the properties and the Create method of the StringComparer class. En el ejemplo se muestra cómo StringComparer diferentes objetos ordenan tres versiones de la letra latina 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 '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
'

Comentarios

Un objeto derivado de la StringComparer clase incluye operaciones de comparación, igualdad y código hash basadas en cadenas que tienen en cuenta las reglas de comparación de mayúsculas y minúsculas y específicas de la referencia cultural.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. Puede utilizar la StringComparer clase para crear una comparación específica del tipo para ordenar los elementos de una colección genérica.You can use the StringComparer class to create a type-specific comparison to sort the elements in a generic collection. Las clases como Hashtable, Dictionary<TKey,TValue>, SortedListy SortedList<TKey,TValue> usan la clase StringComparer para la ordenación.Classes such as Hashtable, Dictionary<TKey,TValue>, SortedList, and SortedList<TKey,TValue> use the StringComparer class for sorting purposes.

Una operación de comparación representada por StringComparer la clase se define como con distinción de mayúsculas y minúsculas o sin distinción de mayúsculas y minúsculas, y se usan reglas de comparación de palabras (con distinción de referencia cultural) o ordinales (no dependientes de la referencia cultural).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. Para obtener más información acerca de las reglas de comparación de System.Globalization.CompareOptionspalabras y ordinales, vea.For more information about word and ordinal comparison rules, see System.Globalization.CompareOptions.

Nota

Puede descargar las tablas de pesos de ordenación, un conjunto de archivos de texto que contienen información sobre los pesos de caracteres que se usan en las operaciones de ordenación y comparación para los sistemas operativos Windows, además de la tabla de elementos de intercalación Unicode predeterminada, que es la última versión de la tabla de pesos de ordenación para Linux y 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 versión específica de la tabla de pesos de ordenación en Linux y macOS depende de la versión de las bibliotecas de componentes internacionales de Unicode instaladas en el sistema.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. Para más información sobre las versiones de los componentes internacionales de Unicode y las versiones de Unicode que implementan, vea la información sobre la descarga de componentes internacionales de Unicode.For information on ICU versions and the Unicode versions that they implement, see Downloading ICU.

Propiedades implementadasImplemented properties

Es posible que se confunda con el StringComparer uso de las propiedades de clase debido a una contradicción aparente.You might be confused about how to use the StringComparer class properties because of a seeming contradiction. La StringComparer clase se declara abstract (MustInherit en Visual Basic), lo que significa que sus miembros solo se pueden invocar en un objeto de una clase derivada StringComparer de la clase.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 contradicción es que cada propiedad de StringComparer la clase se static declaraShared (en Visual Basic), lo que significa que la propiedad se puede invocar sin crear primero una clase derivada.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.

Puede llamar directamente a StringComparer una propiedad porque cada propiedad devuelve realmente una instancia de una clase anónima que se deriva de la StringComparer clase.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. Por consiguiente, el tipo de cada valor de propiedad StringCompareres, que es la clase base de la clase anónima, no el tipo de la propia clase anónima.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. Cada StringComparer propiedad de clase devuelve StringComparer un objeto que admite las reglas de comparación y de mayúsculas y minúsculas predefinidas.Each StringComparer class property returns a StringComparer object that supports predefined case and comparison rules.

Constructores

StringComparer() StringComparer() StringComparer() StringComparer()

Inicializa una nueva instancia de la clase StringComparer.Initializes a new instance of the StringComparer class.

Propiedades

CurrentCulture CurrentCulture CurrentCulture CurrentCulture

Obtiene un objeto StringComparer que realiza una comparación de cadenas con distinción entre mayúsculas y minúsculas usando las reglas de comparación de palabras de la referencia cultural actual.Gets a StringComparer object that performs a case-sensitive string comparison using the word comparison rules of the current culture.

CurrentCultureIgnoreCase CurrentCultureIgnoreCase CurrentCultureIgnoreCase CurrentCultureIgnoreCase

Obtiene un objeto StringComparer que realiza comparaciones de cadenas sin distinción entre mayúsculas y minúsculas usando las reglas de comparación de palabras de la referencia cultural actual.Gets a StringComparer object that performs case-insensitive string comparisons using the word comparison rules of the current culture.

InvariantCulture InvariantCulture InvariantCulture InvariantCulture

Obtiene un objeto StringComparer que realiza una comparación de cadenas con distinción entre mayúsculas y minúsculas utilizando las reglas de comparación de palabras de la referencia cultural de todos los idiomas.Gets a StringComparer object that performs a case-sensitive string comparison using the word comparison rules of the invariant culture.

InvariantCultureIgnoreCase InvariantCultureIgnoreCase InvariantCultureIgnoreCase InvariantCultureIgnoreCase

Obtiene un objeto StringComparer que realiza una comparación de cadenas sin distinción entre mayúsculas y minúsculas utilizando las reglas de comparación de palabras de la referencia cultural de todos los idiomas.Gets a StringComparer object that performs a case-insensitive string comparison using the word comparison rules of the invariant culture.

Ordinal Ordinal Ordinal Ordinal

Obtiene un objeto StringComparer que realiza una comparación de cadenas ordinales donde se hace distinción entre mayúsculas y minúsculas.Gets a StringComparer object that performs a case-sensitive ordinal string comparison.

OrdinalIgnoreCase OrdinalIgnoreCase OrdinalIgnoreCase OrdinalIgnoreCase

Obtiene un objeto StringComparer que realiza una comparación de cadenas ordinales donde no se hace distinción entre mayúsculas y minúsculas.Gets a StringComparer object that performs a case-insensitive ordinal string comparison.

Métodos

Compare(Object, Object) Compare(Object, Object) Compare(Object, Object) Compare(Object, Object)

Cuando se reemplaza en una clase derivada, compara dos objetos y devuelve una indicación de su criterio de ordenación relativo.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)

Cuando se reemplaza en una clase derivada, compara dos cadenas y devuelve una indicación de su criterio de ordenación relativo.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)

Crea un objeto StringComparer que compara cadenas según las reglas de la referencia cultural especificada.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)

Determina si el objeto especificado es igual al objeto actual.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)

Cuando se reemplaza en una clase derivada, indica si dos objetos son iguales.When overridden in a derived class, indicates whether two objects are equal.

Equals(String, String) Equals(String, String) Equals(String, String) Equals(String, String)

Cuando se reemplaza en una clase derivada, indica si dos cadenas son iguales.When overridden in a derived class, indicates whether two strings are equal.

FromComparison(StringComparison) FromComparison(StringComparison) FromComparison(StringComparison) FromComparison(StringComparison)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetHashCode(Object) GetHashCode(Object) GetHashCode(Object) GetHashCode(Object)

Cuando se reemplaza en una clase derivada, obtiene el código hash del objeto especificado.When overridden in a derived class, gets the hash code for the specified object.

GetHashCode(String) GetHashCode(String) GetHashCode(String) GetHashCode(String)

Cuando se reemplaza en una clase derivada, obtiene el código hash de la cadena especificada.When overridden in a derived class, gets the hash code for the specified string.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

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

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

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

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

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)

Se aplica a

Consulte también: