Home > Software engineering >  Print two arrays side by side
Print two arrays side by side

Time:11-17

public static void CategoryX(string categories)
{
    string[] codes = { "A", "B", "C", "D", "E" };
    string[] names = { "FIRST LETTER", "SECOND LETTER", "THIRD LETTER", "FOURTH LETTER", "FIFTH LETTER" };
}

I need the output to look like this:

A FIRST LETTER
B SECOND LETTER
C THIRD LETTER
D FOURTH LETTER
E FIFTH LETTER

I have tried using a for statement using GroupBy which hasn't worked and also tried comparing the two arrays using a bool statement AND made a third array which contains codes and names as elements.

CodePudding user response:

Linq approach

codes.Zip(names, (x, y) => x   " "   y).ToList().ForEach(Console.WriteLine);

CodePudding user response:

You can use a for loop:

string[] result = new string[codes.Length];
for(int i = 0; i < codes.Length; i  )
{
   result[i] = codes[i]   " "   names[i];
   Console.WriteLine(result[i]);
}

This assumes that both arrays have the same length. If you can't assure this, you should check which array is the shortest, e.g. by Math.Min(codes.Length, names.Length). If you don't want to process the data at a further pont, you don't have to use the result array.

As an alternative, you might also look at LINQ's Zip method:

foreach(var entry in codes.Zip(names))
{
   Console.WriteLine(entry.Item1   " "   entry.Item2);
}

If you only want to print the values, via string.Join, this can be even reduced to a one-liner:

Console.WriteLine(string.Join("\n",codes.Zip(names, (c,n) => c   " "   n)));

CodePudding user response:

you can start with a for loop if your two array length is same.

for (int i = 0; i < codes.Length; i  ) 
{
   Console.WriteLine($"{codes[i]} {names[i]}); 
}
  • Related