131 votes

Impression de tout le contenu d'un tableau en C#

J'essaye d'imprimer le contenu d'un tableau après avoir invoqué certaines méthodes qui le modifient, en Java j'utilise :

System.out.print(Arrays.toString(alg.id));

Comment puis-je faire cela en C# ?

0voto

BluePositive Points 21

Si c'est un tableau de chaînes de caractères, vous pouvez utiliser Agrégat

var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D

de cette façon, vous pouvez inverser l'ordre en changeant l'ordre des paramètres comme suit

Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A

0voto

Aldin Ugljanin Points 1

Vous pouvez utiliser la boucle for

    int[] random_numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14}
    int array_length = random_numbers.Length;
    for (int i = 0; i < array_length; i++){
        if(i == array_length - 1){
              Console.Write($"{random_numbers[i]}\n");
        } else{
              Console.Write($"{random_numbers[i]}, ");
         }
     }

-2voto

ugurpolat Points 1

Si vous ne voulez pas utiliser la fonction Array.

public class GArray
{
    int[] mainArray;
    int index;
    int i = 0;

    public GArray()
    {
        index = 0;
        mainArray = new int[4];
    }
    public void add(int addValue)
    {

        if (index == mainArray.Length)
        {
            int newSize = index * 2;
            int[] temp = new int[newSize];
            for (int i = 0; i < mainArray.Length; i++)
            {
                temp[i] = mainArray[i];
            }
            mainArray = temp;
        }
        mainArray[index] = addValue;
        index++;

    }
    public void print()
    {
        for (int i = 0; i < index; i++)
        {
            Console.WriteLine(mainArray[i]);
        }
    }
 }
 class Program
{
    static void Main(string[] args)
    {
        GArray myArray = new GArray();
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        myArray.add(5);
        myArray.add(6);
        myArray.print();
        Console.ReadKey();
    }
}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X