How to use String.Join() in C#
By FoxLearn 3/5/2025 2:13:01 AM 62
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#