How to use String.Join() in C#

By Tan Lee Published on Mar 05, 2025  130
You can utilize String.Join() to convert a collection of items into a single string with a specified separator (like a comma).

For example, How to use String.Join() to convert a List of strings into a comma-separated string:

var list = new List<string>()
{
    "Alice", "Charlie", "Eve"
};

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

Console.WriteLine(names);

This results in the following comma-separated string:

Alice,Charlie,Eve

String.Join() can be applied to a wide range of input types:

  • Any collection type (such as arrays, Lists, IEnumerable).
  • Any item type (strings, integers, etc.).
  • Any separator (comma, newline, tab, etc.).

String.Join() with an array of doubles

You can apply String.Join() to arrays of different types.

For example, converting an array of double values to a string separated by semicolons:

var array = new double[] { 10.5, 20.7, 30.9 };

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

Console.WriteLine(numbers);

This results in the following output:

10.5;20.7;30.9

String.Join() with a custom separator

You can use String.Join() with any separator.

For example, using a tab (\t) as a separator:

var list = new List<string> { "Apple", "Banana", "Cherry" };

string fruits = String.Join("\t", list);

Console.WriteLine(fruits);

This outputs the following tab-separated string:

Apple    Banana    Cherry

String.Join() with a List of complex objects

When working with complex objects (like custom classes), String.Join() converts each item using the ToString() method. If you want to control the output format, use LINQ’s Select() method to define how the object should be converted.

using System.Linq;

var people = new List<Person>()
{
    new Person() { Name = "John", Age = 45 },
    new Person() { Name = "Sarah", Age = 32 },
    new Person() { Name = "Tom", Age = 28 }
};

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

Console.WriteLine(names);

This results in the following output:

John,Sarah,Tom

In this example, String.Join() is used to create a comma-separated list of names from a collection of Person objects. By using Select(), we can specify which property of the object to include.

String.Join() is a versatile method that allows you to combine any collection of items into a single string with your chosen separator. Whether you’re working with simple data types like strings and numbers or more complex objects, it’s an essential tool for handling collections efficiently.