CollectionsUtil Class

Definition

Crea colecciones que omiten las mayúsculas y minúsculas en las cadenas.Creates collections that ignore the case in strings.

public ref class CollectionsUtil
public class CollectionsUtil
type CollectionsUtil = class
Public Class CollectionsUtil
Inheritance
CollectionsUtil

Examples

En el ejemplo siguiente se utilizan dos colecciones, una tabla hash y una lista ordenada, para contener los valores de rellenado de un grupo de ciudades.The following example uses two collections, a hash table and a sorted list, to hold population values for a group of cities. Los valores se recuperan de las colecciones usando los nombres de ciudades como claves.The values are retrieved from the collections by using the city names as keys. Los nombres de ciudades están en mayúsculas y minúsculas para mostrar su uso como claves que no distinguen mayúsculas de minúsculas.The city names are in mixed case to show their use as case-insensitive keys.

#using <System.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Collections::Specialized;

ref class TestCollectionsUtils
{
public:
    static void Main()
    {
        Hashtable^ population1 = CollectionsUtil::CreateCaseInsensitiveHashtable();

        population1["Trapperville"] = 15;
        population1["Doggerton"] = 230;
        population1["New Hollow"] = 1234;
        population1["McHenry"] = 185;

        // Select cities from the table using mixed case.
        Console::WriteLine("Case insensitive hashtable results:\n");
        Console::WriteLine("{0}'s population is: {1}", "Trapperville", population1["trapperville"]);
        Console::WriteLine("{0}'s population is: {1}", "Doggerton", population1["DOGGERTON"]);
        Console::WriteLine("{0}'s population is: {1}", "New Hollow", population1["New hoLLow"]);
        Console::WriteLine("{0}'s population is: {1}", "McHenry", population1["MchenrY"]);

        SortedList^ population2 = CollectionsUtil::CreateCaseInsensitiveSortedList();

        for each (String^ city in population1->Keys)
        {
            population2->Add(city, population1[city]);
        }

        // Select cities from the sorted list using mixed case.
        Console::WriteLine("\nCase insensitive sorted list results:\n");
        Console::WriteLine("{0}'s population is: {1}", "Trapperville", population2["trapPeRVille"]);
        Console::WriteLine("{0}'s population is: {1}", "Doggerton", population2["dOGGeRtON"]);
        Console::WriteLine("{0}'s population is: {1}", "New Hollow", population2["nEW hOLLOW"]);
        Console::WriteLine("{0}'s population is: {1}", "McHenry", population2["MchEnrY"]);
    }
};

int main()
{
    TestCollectionsUtils::Main();
}

// This program displays the following output to the console
//
// Case insensitive hashtable results:
//
// Trapperville's population is: 15
// Doggerton's population is: 230
// New Hollow's population is: 1234
// McHenry's population is: 185
//
// Case insensitive sorted list results:
//
// Trapperville's population is: 15
// Doggerton's population is: 230
// New Hollow's population is: 1234
// McHenry's population is: 185
using System;
using System.Collections;
using System.Collections.Specialized;

class TestCollectionsUtils
{
    public static void Main()
    {
        Hashtable population1 = CollectionsUtil.CreateCaseInsensitiveHashtable();

        population1["Trapperville"] = 15;
        population1["Doggerton"] = 230;
        population1["New Hollow"] = 1234;
        population1["McHenry"] = 185;

        // Select cities from the table using mixed case.
        Console.WriteLine("Case insensitive hashtable results:\n");
        Console.WriteLine("{0}'s population is: {1}", "Trapperville", population1["trapperville"]);
        Console.WriteLine("{0}'s population is: {1}", "Doggerton", population1["DOGGERTON"]);
        Console.WriteLine("{0}'s population is: {1}", "New Hollow", population1["New hoLLow"]);
        Console.WriteLine("{0}'s population is: {1}", "McHenry", population1["MchenrY"]);

        SortedList population2 = CollectionsUtil.CreateCaseInsensitiveSortedList();

        foreach (string city in population1.Keys)
        {
           population2.Add(city, population1[city]);
        }

        // Select cities from the sorted list using mixed case.
        Console.WriteLine("\nCase insensitive sorted list results:\n");
        Console.WriteLine("{0}'s population is: {1}", "Trapperville", population2["trapPeRVille"]);
        Console.WriteLine("{0}'s population is: {1}", "Doggerton", population2["dOGGeRtON"]);
        Console.WriteLine("{0}'s population is: {1}", "New Hollow", population2["nEW hOLLOW"]);
        Console.WriteLine("{0}'s population is: {1}", "McHenry", population2["MchEnrY"]);
    }
}

// This program displays the following output to the console
//
// Case insensitive hashtable results:
//
// Trapperville's population is: 15
// Doggerton's population is: 230
// New Hollow's population is: 1234
// McHenry's population is: 185
//
// Case insensitive sorted list results:
//
// Trapperville's population is: 15
// Doggerton's population is: 230
// New Hollow's population is: 1234
// McHenry's population is: 185
Imports System.Collections
Imports System.Collections.Specialized

Class TestCollectionsUtils
    Public Shared Sub Main()
        Dim population1 As Hashtable = CollectionsUtil.CreateCaseInsensitiveHashtable()

        population1("Trapperville") = 15
        population1("Doggerton") = 230
        population1("New Hollow") = 1234
        population1("McHenry") = 185

        ' Select cities from the table using mixed case.
        Console.WriteLine("Case insensitive hashtable results:" + vbNewLine)
        Console.WriteLine("{0}'s population is: {1}", "Trapperville", population1("trapperville"))
        Console.WriteLine("{0}'s population is: {1}", "Doggerton", population1("DOGGERTON"))
        Console.WriteLine("{0}'s population is: {1}", "New Hollow", population1("New hoLLow"))
        Console.WriteLine("{0}'s population is: {1}", "McHenry", population1("MchenrY"))

        Dim population2 As SortedList = CollectionsUtil.CreateCaseInsensitiveSortedList()

        For Each city As String In population1.Keys
            population2.Add(city, population1(city))
        Next city

        ' Select cities from the sorted list using mixed case.
        Console.WriteLine(vbNewLine + "Case insensitive sorted list results:" + vbNewLine)
        Console.WriteLine("{0}'s population is: {1}", "Trapperville", population2("trapPeRVille"))
        Console.WriteLine("{0}'s population is: {1}", "Doggerton", population2("dOGGeRtON"))
        Console.WriteLine("{0}'s population is: {1}", "New Hollow", population2("nEW hOLLOW"))
        Console.WriteLine("{0}'s population is: {1}", "McHenry", population2("MchEnrY"))
    End Sub
End Class

' This program displays the following output to the console
'
' Case insensitive hashtable results:
'
' Trapperville's population is: 15
' Doggerton's population is: 230
' New Hollow's population is: 1234
' McHenry's population is: 185
'
' Case insensitive sorted list results:
'
' Trapperville's population is: 15
' Doggerton's population is: 230
' New Hollow's population is: 1234
' McHenry's population is: 185

Remarks

Estos métodos generan una instancia que no distingue entre mayúsculas y minúsculas de la colección mediante implementaciones que no distinguen entre mayúsculas y minúsculas del proveedor de código hash y el comparador.These methods generate a case-insensitive instance of the collection using case-insensitive implementations of the hash code provider and the comparer. La instancia resultante se puede usar como cualquier otra instancia de esa clase, aunque puede comportarse de forma diferente.The resulting instance can be used like any other instances of that class, although it may behave differently.

Por ejemplo, supongamos que se van a agregar dos objetos con las claves "Hello" y "HELLO" a una tabla hash.For example, suppose two objects with the keys "hello" and "HELLO" are to be added to a hash table. Una tabla hash que distingue entre mayúsculas y minúsculas crearía dos entradas diferentes; mientras que, una tabla hash que no distingue entre mayúsculas y minúsculas produciría una excepción al agregar el segundo objeto.A case-sensitive hash table would create two different entries; whereas, a case-insensitive hash table would throw an exception when adding the second object.

Constructors

CollectionsUtil()

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

Methods

CreateCaseInsensitiveHashtable()

Crea una nueva instancia que no tiene en cuenta el uso de mayúsculas y minúsculas de la clase Hashtable con la capacidad inicial predeterminada.Creates a new case-insensitive instance of the Hashtable class with the default initial capacity.

CreateCaseInsensitiveHashtable(IDictionary)

Copia las entradas del diccionario especificado a una nueva instancia que no distingue entre mayúsculas y minúsculas de la clase Hashtable con la misma capacidad inicial que el número de entradas copiadas.Copies the entries from the specified dictionary to a new case-insensitive instance of the Hashtable class with the same initial capacity as the number of entries copied.

CreateCaseInsensitiveHashtable(Int32)

Crea una nueva instancia que no tiene en cuenta el uso de mayúsculas y minúsculas de la clase Hashtable con la capacidad inicial especificada.Creates a new case-insensitive instance of the Hashtable class with the specified initial capacity.

CreateCaseInsensitiveSortedList()

Crea una nueva instancia de la clase SortedList, que omite el uso de mayúsculas y minúsculas en las cadenas.Creates a new instance of the SortedList class that ignores the case of strings.

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)
GetHashCode()

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

(Inherited from Object)
GetType()

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

(Inherited from Object)
MemberwiseClone()

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

(Inherited from Object)
ToString()

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

(Inherited from Object)

Applies to

Thread Safety

Un Hashtable puede admitir un escritor y varios lectores simultáneamente.A Hashtable can support one writer and multiple readers concurrently. Para admitir varios escritores, todas las operaciones se deben realizar a través del contenedor devuelto por el método Synchronized(Hashtable).To support multiple writers, all operations must be done through the wrapper returned by the Synchronized(Hashtable) method.

Un SortedList puede admitir varios lectores simultáneamente, siempre y cuando no se modifique la colección.A SortedList can support multiple readers concurrently, as long as the collection is not modified. Para garantizar la seguridad para subprocesos del SortedList, todas las operaciones se deben realizar a través del contenedor devuelto por el método Synchronized(SortedList).To guarantee the thread safety of the SortedList, all operations must be done through the wrapper returned by the Synchronized(SortedList) method.

La enumeración a través de una colección no es intrínsecamente un procedimiento seguro para subprocesos.Enumerating through a collection is intrinsically not a thread safe procedure. Incluso cuando una colección está sincronizada, otros subprocesos todavía pueden modificarla, lo que hace que el enumerador produzca una excepción.Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. Con el fin de garantizar la seguridad para la ejecución de subprocesos durante la enumeración, se puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

See also