Este tema aún no ha recibido ninguna valoración - Valorar este tema

NameValueCollection (Clase)

Representa una colección de claves de String y valores de String asociados a los que se puede obtener acceso con la clave o con el índice.

Espacio de nombres: System.Collections.Specialized
Ensamblado: System (en system.dll)

[SerializableAttribute] 
public class NameValueCollection : NameObjectCollectionBase
/** @attribute SerializableAttribute() */ 
public class NameValueCollection extends NameObjectCollectionBase
SerializableAttribute 
public class NameValueCollection extends NameObjectCollectionBase

Esta colección se basa en la clase NameObjectCollectionBase. Sin embargo, a diferencia de NameObjectCollectionBase, esta clase almacena varios valores de cadena en una sola clave.

Esta clase se utiliza para encabezados, cadenas de consulta y datos de formulario.

Cada elemento es un par de clave y valor.

La capacidad de un objeto NameValueCollection es el número de elementos que puede contener. La capacidad inicial predeterminada de NameValueCollection es cero. Cuando se agregan elementos a un objeto NameValueCollection, la capacidad aumenta automáticamente según sea necesario mediante la reasignación.

El proveedor de código hash asigna códigos hash para las claves del objeto NameValueCollection. El proveedor predeterminado de códigos hash es CaseInsensitiveHashCodeProvider.

El comparador determina si dos claves son iguales. El comparador predeterminado es CaseInsensitiveComparer.

En el caso de la versión 1.0 de .NET Framework, esta clase utiliza comparaciones de cadenas que tienen en cuenta la referencia cultural. Sin embargo, en la versión 1.1 de .NET Framework y versiones posteriores, esta clase utiliza CultureInfo.InvariantCulture a la hora de comparar cadenas. Para obtener más información sobre la forma en que la referencia cultural afecta a las comparaciones y a la ordenación, vea Comparar y ordenar datos para una referencia cultural específicaComparar y ordenar datos para una referencia cultural específica y Realizar operaciones de cadenas que no distinguen entre referencias culturales.

Se permite referencia de objeto null (Nothing en Visual Basic) como una clave o como un valor.

Nota de precauciónPrecaución

El método Get no distingue entre referencia de objeto null (Nothing en Visual Basic) que se ha devuelto porque no se ha encontrado la clave especificada y referencia de objeto null (Nothing en Visual Basic) que se ha devuelto porque el valor asociado a la clave es referencia de objeto null (Nothing en Visual Basic).

using System;
using System.Collections;
using System.Collections.Specialized;

public class SamplesNameValueCollection  {

   public static void Main()  {

      // Creates and initializes a new NameValueCollection.
      NameValueCollection myCol = new NameValueCollection();
      myCol.Add( "red", "rojo" );
      myCol.Add( "green", "verde" );
      myCol.Add( "blue", "azul" );
      myCol.Add( "red", "rouge" );

      // Displays the values in the NameValueCollection in two different ways.
      Console.WriteLine( "Displays the elements using the AllKeys property and the Item (indexer) property:" );
      PrintKeysAndValues( myCol );
      Console.WriteLine( "Displays the elements using GetKey and Get:" );
      PrintKeysAndValues2( myCol );

      // Gets a value either by index or by key.
      Console.WriteLine( "Index 1 contains the value {0}.", myCol[1] );
      Console.WriteLine( "Key \"red\" has the value {0}.", myCol["red"] );
      Console.WriteLine();

      // Copies the values to a string array and displays the string array.
      String[] myStrArr = new String[myCol.Count];
      myCol.CopyTo( myStrArr, 0 );
      Console.WriteLine( "The string array contains:" );
      foreach ( String s in myStrArr )
         Console.WriteLine( "   {0}", s );
      Console.WriteLine();

      // Searches for a key and deletes it.
      myCol.Remove( "green" );
      Console.WriteLine( "The collection contains the following elements after removing \"green\":" );
      PrintKeysAndValues( myCol );

      // Clears the entire collection.
      myCol.Clear();
      Console.WriteLine( "The collection contains the following elements after it is cleared:" );
      PrintKeysAndValues( myCol );

   }

   public static void PrintKeysAndValues( NameValueCollection myCol )  {
      IEnumerator myEnumerator = myCol.GetEnumerator();
      Console.WriteLine( "   KEY        VALUE" );
      foreach ( String s in myCol.AllKeys )
         Console.WriteLine( "   {0,-10} {1}", s, myCol[s] );
      Console.WriteLine();
   }

   public static void PrintKeysAndValues2( NameValueCollection myCol )  {
      Console.WriteLine( "   [INDEX] KEY        VALUE" );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   [{0}]     {1,-10} {2}", i, myCol.GetKey(i), myCol.Get(i) );
      Console.WriteLine();
   }


}

/*

This code produces the following output.

Displays the elements using the AllKeys property and the Item (indexer) property:
   KEY        VALUE
   red        rojo,rouge
   green      verde
   blue       azul

Displays the elements using GetKey and Get:
   [INDEX] KEY        VALUE
   [0]     red        rojo,rouge
   [1]     green      verde
   [2]     blue       azul

Index 1 contains the value verde.
Key "red" has the value rojo,rouge.

The string array contains:
   rojo,rouge
   verde
   azul

The collection contains the following elements after removing "green":
   KEY        VALUE
   red        rojo,rouge
   blue       azul

The collection contains the following elements after it is cleared:
   KEY        VALUE


*/

import System.*;
import System.Collections.*;
import System.Collections.Specialized.*;

public class SamplesNameValueCollection
{
    public static void main(String[] args)
    {
        // Creates and initializes a new NameValueCollection.
        NameValueCollection myCol = new NameValueCollection();
        myCol.Add("red", "rojo");
        myCol.Add("green", "verde");
        myCol.Add("blue", "azul");
        myCol.Add("red", "rouge");
        // Displays the values in the NameValueCollection in two different ways.
        Console.WriteLine("Displays the elements using the AllKeys property" 
            + " and the Item (indexer) property:");
        PrintKeysAndValues(myCol);
        Console.WriteLine("Displays the elements using GetKey and Get:");
        PrintKeysAndValues2(myCol);
        // Gets a value either by index or by key.
        Console.WriteLine("Index 1 contains the value {0}.", myCol.get_Item(1));
        Console.WriteLine("Key \"red\" has the value {0}.",
            myCol.get_Item("red"));
        Console.WriteLine();
        // Copies the values to a string array and displays the string array.
        String myStrArr[] = new String[myCol.get_Count()];
        myCol.CopyTo(myStrArr, 0);
        Console.WriteLine("The string array contains:");
        for (int iCtr = 0; iCtr < myStrArr.get_Length(); iCtr++) {
            String s = myStrArr[iCtr];
            Console.WriteLine("   {0}", s);
        }
        Console.WriteLine();
        // Searches for a key and deletes it.
        myCol.Remove("green");
        Console.WriteLine("The collection contains the following elements " 
            + "after removing \"green\":");
        PrintKeysAndValues(myCol);
        // Clears the entire collection.
        myCol.Clear();
        Console.WriteLine("The collection contains the following elements " 
            + "after it is cleared:");
        PrintKeysAndValues(myCol);
    } //main

    public static void PrintKeysAndValues(NameValueCollection myCol)
    {
        IEnumerator myEnumerator = myCol.GetEnumerator();
        Console.WriteLine("   KEY        VALUE");
        for (int iCtr = 0; iCtr < myCol.get_Count(); iCtr++) {
            String s = myCol.get_AllKeys()[iCtr];
            Console.WriteLine("   {0,-10} {1}", s, myCol.get_Item(s));
        }
        Console.WriteLine();
    } //PrintKeysAndValues

    public static void PrintKeysAndValues2(NameValueCollection myCol)
    {
        Console.WriteLine("   [INDEX] KEY        VALUE");
        for (int i = 0; i < myCol.get_Count(); i++) {
            Console.WriteLine("   [{0}]     {1,-10} {2}",
                System.Convert.ToString(i), System.Convert.ToString(
                myCol.GetKey(i)), System.Convert.ToString(myCol.Get(i)));
        }
        Console.WriteLine();
    } //PrintKeysAndValues2
} //SamplesNameValueCollection 

/*
    This code produces the following output.
    Displays the elements using the AllKeys property and the Item 
    (indexer) property:
    KEY        VALUE
    red        rojo,rouge
    green      verde
    blue       azul

    Displays the elements using GetKey and Get:
    [INDEX] KEY        VALUE
    [0]     red        rojo,rouge
    [1]     green      verde
    [2]     blue       azul
     
    Index 1 contains the value verde.
    Key "red" has the value rojo,rouge.
    
    The string array contains:
    rojo,rouge
    verde
    azul

    The collection contains the following elements after removing "green":
    KEY        VALUE
    red        rojo,rouge
    blue       azul

    The collection contains the following elements after it is cleared:
    KEY        VALUE       
*/

Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Esta implementación no proporciona un contenedor sincronizado (seguro para la ejecución de subprocesos) para NameValueCollection, pero las clases derivadas pueden crear sus propias versiones sincronizadas de NameValueCollection mediante la propiedad SyncRoot de la clase NameObjectCollectionBase.

La enumeración en una colección es un procedimiento que no es intrínsecamente seguro para la ejecución de subprocesos. Incluso cuando una colección está sincronizada, otros subprocesos todavía pueden modificarla, lo que hace que el enumerador produzca una excepción. 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 debidas a cambios efectuados por otros subprocesos.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0
¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar