How to convert a List to a string in C#
By Tan Lee Published on Mar 05, 2025 126
Using String.Join()
String.Join()
is one of the easiest ways to convert a List
to a string. By providing a delimiter, you can generate a single string that separates the items. Below is an example where a List<string>
is converted to a string using a comma as the delimiter:
var list = new List<string>() { "Alice", "Bob", "Charlie", "Dave", "Eve" }; string names = String.Join(",", list); Console.WriteLine(names);
This will output:
Alice,Bob,Charlie,Dave,Eve
Notice that String.Join()
ensures there’s no trailing comma at the end.
You can use String.Join()
with any type of list, as it calls ToString()
on each item internally.
Here’s an example where a List<int>
is converted to a string, with each number on a new line:
var list = new List<int>() { 10, 20, 30, 40, 50 }; string numbers = String.Join(Environment.NewLine, list); Console.WriteLine(numbers);
This will output the integers as a newline-separated string:
10 20 30 40 50
Using StringBuilder and a foreach Loop
Another method to convert a List
to a string is by using a foreach
loop in combination with a StringBuilder
. This method gives you more control over the process and allows you to manipulate the string more flexibly.
Here’s an example where we convert a List<string>
to a comma-separated string using a loop and StringBuilder
:
using System.Text; var list = new List<string>() { "Tom", "Jerry", "Spike" }; var sb = new StringBuilder(); var delimiter = ","; foreach(var name in list) { sb.Append(name); sb.Append(delimiter); } // Remove the trailing delimiter if (sb.Length > 0) sb.Remove(sb.Length - 1, 1); string result = sb.ToString(); Console.WriteLine(result);
This will output:
Tom,Jerry,Spike
As you can see, the trailing comma is removed after the loop by using StringBuilder.Remove()
. This approach avoids the need to conditionally append the delimiter during the loop, making the code more efficient.
String.Join()
is great for simplicity and works well for basic cases with a consistent delimiter.StringBuilder
with a loop is a bit more flexible and allows for fine-tuning, like removing trailing delimiters.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization