18

How do I print a list of string arrays? I can do it from string[] using Console.WriteLine, but if I do that for a list with foreach it just prints out System.String[]. How do I write an index when using a foreach?

Federico Navarrete
  • 2,641
  • 5
  • 39
  • 64
atilas1
  • 341
  • 2
  • 3
  • 9
  • Use the index and print it – A3006 Feb 08 '17 at 11:38
  • 2
    if you want to print array values, you cannot just pass array to `Console.WriteLine` you should either print each item of array separately or convert array to string and then print that string. E.g. with `String.Join(",", yourArray)` – Sergey Berezovskiy Feb 08 '17 at 11:40

5 Answers5

44

The simplest way to achieve this is: using String.Join

string[] arr = new string[] { "one", "two", "three", "four" };
Console.WriteLine(String.Join("\n", arr)); 

Hope this helps.

Federico Navarrete
  • 2,641
  • 5
  • 39
  • 64
PulkitG
  • 552
  • 3
  • 12
5

So you have list of string arrays, like this:

 List<string[]> data = new List<string[]>() {
   new string[] {"A", "B", "C"},
   new string[] {"1", "2"},
   new string[] {"x", "yyyy", "zzz", "final"},
 };

To print on, say, the Console, you can implement nested loops:

 foreach (var array in data) {
   Console.WriteLine();

   foreach (var item in array) {
     Console.Write(" ");
     Console.Write(item); 
   }
 }

Or Join the items into the single string and then print it:

 using System.Linq;
 ...

 string report = string.Join(Environment.NewLine, data
   .Select(array => string.Join(" ", array)));

 Console.Write(report);

Or combine both methods:

 foreach (var array in data) 
   Console.WriteLine(string.Join(" ", array));
Dmitry Bychenko
  • 165,109
  • 17
  • 150
  • 199
5

This works for me:

var strArray = new string[] {"abc","def","asd" };
strArray.ToList().ForEach(Console.WriteLine);
master2080
  • 346
  • 3
  • 14
2
string[] arr = new string[2]{"foo","zoo"}; // sample Initialize.

// Loop over strings.
foreach (string s in arr)
{
    Console.WriteLine(s);
}

The console output:

foo
zoo
Alexey Subach
  • 10,803
  • 7
  • 33
  • 58
user114649
  • 21
  • 1
0

In a string array to get the index you do it:

string[] names = new string[3] { "Matt", "Joanne", "Robert" };

int counter = 0;
foreach(var name in names.ToList())
{
 Console.WriteLine(counter.ToString() + ":-" + name);
 counter++;
}
Rui Estreito
  • 252
  • 1
  • 10