C# | Convertir una array de un tipo en una array de otro tipo

El método Array.ConvertAll(TInput[], Converter<TInput, TOutput>) se utiliza para convertir una array de un tipo en una array de otro tipo.

Sintaxis:

public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, 
Converter<TInput,TOutput> converter);

Aquí, TInput y TOutput son la array de origen y la array de destino, respectivamente.

Parámetros:

array: es la array unidimensional de base cero para convertir a un tipo de destino.
convertidor: Es un convertidor que convierte cada elemento de un tipo a otro tipo.

Valor devuelto: este método devuelve una array del tipo de destino que contiene los elementos convertidos de la array de origen.

Excepción: este método lanza ArgumentNullException si la array es nula o el convertidor es nulo.

Los siguientes programas ilustran el uso del método Array.ConvertAll(TInput[], Converter<TInput, TOutput>)

Ejemplo 1:

// C# program to demonstrate
// Array.ConvertAll() Method
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing
            // new the Array of int
            int[] myArr = {10, 20, 30, 40};
  
            // Display the values of the myArr.
            Console.WriteLine("Initial Array:");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(myArr);
  
            // converting int myArr to String conarr
            String[] conarr = Array.ConvertAll(myArr, 
              new Converter<int, String>(intToString));
  
            // Display the values of the myArr.
            Console.WriteLine("Converted Array:");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(conarr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(int[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // intToString
    public static String intToString(int pf)
    {
        return pf.ToString();
    }
}
Producción:

Initial Array:
10
20
30
40

Converted Array:
10
20
30
40

Ejemplo 2:

// C# program to demonstrate
// Array.ConvertAll() Method
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing new 
            // the Array of int with null value
            int[] myArr = null;
  
            // converting int myArr to String conarr
            String[] conarr = Array.ConvertAll(myArr, 
             new Converter<int, String>(intToString));
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(conarr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
  
    // Defining the method
    // intToString
    public static String intToString(int pf)
    {
        return pf.ToString();
    }
}
Producción:

Exception Thrown: System.ArgumentNullException

Referencia:

Publicación traducida automáticamente

Artículo escrito por RohitPrasad3 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 *