C# | Clase StringDictionaryStringDictionary Class – Part 1

StringDictionary es una colección especializada. Esta clase viene bajo el espacio de nombres System.Collections.Specialized . Solo permite claves de string y valores de string. Sufre de problemas de rendimiento. Implementa una tabla hash con la clave y el valor tipificado fuertemente para que sean strings en lugar de objetos.

Características:

  • Una clave no puede ser nula , pero un valor sí.
  • La clave se maneja sin distinguir entre mayúsculas y minúsculas, es decir, se traduce a minúsculas antes de usarse con el diccionario de strings.
  • El constructor StringDictionary() inicializa una nueva instancia de la clase StringDictionary.

Constructores

Constructor Descripción
Diccionario de strings() Inicializa una nueva instancia de la clase StringDictionary.

Ejemplo:

// C# code to create a StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
  
        // Displaying the keys and values in StringDictionary
        foreach(DictionaryEntry dic in myDict)
        {
            Console.WriteLine(dic.Key + " " + dic.Value);
        }
    }
}

Producción:

d Dog
b Banana
c Cat
e Elephant
a Apple

Propiedades

Propiedad Descripción
Contar Obtiene el número de pares clave/valor en StringDictionary.
Está sincronizado Obtiene un valor que indica si el acceso a StringDictionary está sincronizado (seguro para subprocesos).
Elemento[String] Obtiene o establece el valor asociado a la clave especificada.
Llaves Obtiene una colección de claves en StringDictionary.
SyncRoot Obtiene un objeto que se puede usar para sincronizar el acceso a StringDictionary.
Valores Obtiene una colección de valores en StringDictionary.

Ejemplo:

// C# code illustrate the Properties of
// StringDictionary class
using System; 
using System.Collections; 
using System.Collections.Specialized; 
    
class GFG { 
    
    // Driver code 
    public static void Main() 
    { 
    
        // Creating a StringDictionary named myDict 
        StringDictionary myDict = new StringDictionary(); 
    
        // Adding key and value into the StringDictionary 
        myDict.Add("3", "prime & odd"); 
        myDict.Add("2", "prime & even"); 
        myDict.Add("4", "non-prime & even"); 
        myDict.Add("9", "non-prime & odd"); 
    
    
        // -------- Values Property --------
          
        // Getting a collection of values 
        // in the StringDictionary 
        foreach(string val in myDict.Values) 
        { 
            Console.WriteLine(val); 
        } 
          
          
        // -------- IsSynchronized Property --------
          
        // Checking if StringDictionary 
        // is synchronized (thread safe) 
        Console.WriteLine(myDict.IsSynchronized); 
    } 
} 

Producción:

prime & even
prime & odd
non-prime & odd
non-prime & even
False

Métodos

Método Descripción
Agregar (String, String) Agrega una entrada con la clave y el valor especificados en StringDictionary.
Claro() Elimina todas las entradas del StringDictionary.
Contiene clave (string) Determina si StringDictionary contiene una clave específica.
ContieneValor(String) Determina si StringDictionary contiene un valor específico.
Copiar a (array, Int32) Copia los valores del diccionario de strings en una instancia de Array unidimensional en el índice especificado.
Es igual a (Objeto) Determina si el objeto especificado es igual al objeto actual.
ObtenerEnumerador() Devuelve un enumerador que itera a través del diccionario de strings.
Obtener código hash() Sirve como la función hash predeterminada.
ObtenerTipo() Obtiene el Tipo de la instancia actual.
MemberwiseClone() Crea una copia superficial del objeto actual.
Eliminar (String) Elimina la entrada con la clave especificada del diccionario de strings.
Enstringr() Devuelve una string que representa el objeto actual.

Ejemplo 1:

// C# code to remove the entry
// with the specified key from
// the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
        myDict.Add("F", "Fish");
  
        // Displaying the keys and values in StringDictionary
        Console.WriteLine("The number of key/value pairs are : " + myDict.Count);
  
        // Removing the entry with the specified
        // key from the StringDictionary
        myDict.Remove("D");
  
        // Displaying the keys and values in StringDictionary
        Console.WriteLine("The number of key/value pairs are : " + myDict.Count);
    }
}

Producción:

The number of key/value pairs are : 6
The number of key/value pairs are : 5

Ejemplo 2:

// C# code to copy StringDictionary
// to Array at the specified index
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a StringDictionary named myDict
        StringDictionary myDict = new StringDictionary();
  
        // Adding key and value into the StringDictionary
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
  
        // Creating an Array named myArr
        DictionaryEntry[] myArr = { new DictionaryEntry(),
                                    new DictionaryEntry(),
                                    new DictionaryEntry(),
                                    new DictionaryEntry(),
                                    new DictionaryEntry() };
  
        // Copying StringDictionary to
        // Array at the specified index
        myDict.CopyTo(myArr, 0);
  
        // Displaying key and value pairs in Array myArr
        for (int i = 0; i < myArr.Length; i++) {
            Console.WriteLine(myArr[i].Key + " " + myArr[i].Value);
        }
    }
}

Producción:

d Dog
b Banana
c Cat
e Elephant
a Apple

Referencia:

Publicación traducida automáticamente

Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *