-1

If I have a list

var myList = new List<string>();

and I add a couple of strings

myList.Add("Hello");
myList.Add("World");
myList.Add("!");

How do I print the entire list on one line? If I try Console.WriteLine(myList); the console prints "System.Collections.Generic.List`1[System.String]" instead of "Hello World !". I've tried

myList.ForEach(Console.WriteLine); 

but that prints "Hello", "World" and "!" on separate lines instead of on one line. How would I go about printing the list on one line?

Erik Norberg
  • 53
  • 2
  • 7

2 Answers2

3

Use string.Join like this

  var myList = new List<String>{ "Hello", "world", "!" };
  Console.WriteLine(string.Join(" ", myList ));

The result will be: Hello world !

mrbm
  • 1,136
  • 1
  • 12
  • 36
0

You can try to Join all the items of myList into single string, then print it:

 // Hello
 // World
 // !
 Console.WriteLine(string.Join(Environment.NewLine, myList));

Or (let's change delimiter)

 // Hello World !
 Console.WriteLine(string.Join(" ", myList));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215