C# – Using String.Join()

You can use String.Join() to convert a collection of items to a string with a separator (such as a comma). Here’s an example of using String.Join() to convert a List of strings to a comma-separated string:

var list = new List<string>()
{
    "Bob", "Linda", "Teddy"
};

string names = String.Join(",", list);

Console.WriteLine(names);
Code language: C# (cs)

This results in the following comma-separated string:

Bob,Linda,TeddyCode language: plaintext (plaintext)

String.Join() can be used on wide variety of input:

  • Any collection type (array, List, IEnumerable).
  • Any item type (string, int, etc…).
  • Any separator (comma, newline, tab, etc…).

I’ll show a few practical examples.

String.Join() with an array of integers

You can use String.Join() on any collection type and any item type. Here’s an example of using String.Join() to convert an array of integers to a comma-separated string:

var array = new int[] { 1, 2, 3, 4 };

string numbers = String.Join(",", array);

Console.WriteLine(numbers);
Code language: C# (cs)

This outputs the following comma-separated string (which you can then parse back into an array of integers):

1,2,3,4Code language: plaintext (plaintext)

String.Join() with a newline

You can use String.Join() with any separator you choose, including a newline. Here’s an example of using a newline as the separator:

var list = new string[] { "Bob", "Linda", "Teddy" };

string names = String.Join(Environment.NewLine, list);

Console.WriteLine(names);
Code language: C# (cs)

This outputs the following newline-separated string (one item per line):

Bob
Linda
TeddyCode language: plaintext (plaintext)

Environment.NewLine gives you the current environment’s default newline character (\n or \r\n). You can either use that or explicitly specify the newline character to use. Here’s an example of explicitly using \n as newline separator:

string names = String.Join('\n', list);
Code language: C# (cs)

String.Join() with a List of objects

String.Join() converts each item to a string with ToString(). This is a problem if the type doesn’t have ToString() overridden. A nice, flexible way to solve this is by using Select() (Linq) and then use String.Join() on the result. Here’s an example:

using System.Linq;

var list = new List<Person>()
{
    new Person() { Name = "Bob", Age = 40 },
    new Person() { Name = "Linda", Age = 39 },
    new Person() { Name = "Tina", Age = 13 }
};

string names = String.Join(",", list.Select(p => p.Name));

Console.WriteLine(names);
Code language: C# (cs)

This outputs just the names as a comma-separated list:

Bob,Linda,TinaCode language: plaintext (plaintext)