C# | Copie StringCollection en el índice especificado de la array – Part 1

La clase StringCollection es una nueva adición a la biblioteca de clases de .NET Framework que representa una colección de strings. La clase StringCollection se define en el espacio de nombres System.Collections.Specialized .

El método StringCollection.CopyTo(String[], Int32) se usa para copiar todos los valores de StringCollection en una array unidimensional de strings que comienza en el índice especificado de la array de destino.

Sintaxis:

public void CopyTo (string[] array, int index);

Parámetros:

  • array : Es la array unidimensional de strings que es el destino de los elementos copiados de StringCollection. El Array debe tener una indexación basada en cero.
  • índice: es el índice basado en cero en la array en el que comienza la copia.

Excepciones:

  • ArgumentNullException: si la array es nula.
  • ArgumentOutOfRangeException: si el índice es menor que cero.
  • InvalidCastException: si el tipo de StringCollection de origen no se puede convertir automáticamente al tipo de array de destino.
  • ArgumentException: si la array es multidimensional o la cantidad de elementos en la StringCollection de origen es mayor que el espacio disponible desde el índice hasta el final de la array de destino.

Nota:

  • La array especificada debe ser de un tipo compatible.
  • Este método es una operación O(n), donde n es Count.

A continuación se dan algunos ejemplos para entender la implementación de una mejor manera:

Ejemplo 1:

// C# code to copy StringCollection to array,
// starting at the specified index of
// the target array
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr1
        String[] myArr1 = new String[] { "A", "B", "C", "D", "E" };
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr1);
  
        // creating a String array named myArr2
        String[] myArr2 = new String[myCol.Count];
  
        // Copying StringCollection to array myArr2
        // starting from index 0
        myCol.CopyTo(myArr2, 0);
  
        // Displaying elements in array myArr2
        for (int i = 0; i < myArr2.Length; i++) {
            Console.WriteLine(myArr2[i]);
        }
    }
}

Producción:

A
B
C
D
E

Ejemplo 2:

// C# code to copy StringCollection to array,
// starting at the specified index of
// the target array
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // creating a StringCollection named myCol
        StringCollection myCol = new StringCollection();
  
        // creating a string array named myArr1
        String[] myArr1 = new String[] {"1", "2", "3",
                                       "4", "5", "6"};
  
        // Copying the elements of a string
        // array to the end of the StringCollection.
        myCol.AddRange(myArr1);
  
        // creating a String array named myArr2
        String[] myArr2 = new String[myCol.Count];
  
        // Copying StringCollection to array myArr2
        // starting from index -1
        // This should raise exception "ArgumentOutOfRangeException"
        // as index is less than 0
        myCol.CopyTo(myArr2, -1);
  
        // Displaying elements in array myArr2
        for (int i = 0; i < myArr2.Length; i++) {
            Console.WriteLine(myArr2[i]);
        }
    }
}

Producción:

Excepción no controlada:
System.ArgumentOutOfRangeException: el valor debe ser >= 0.
Nombre del parámetro: índice de destino

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 *