There are two good ways to convert a List<T> to a string:
- Use String.Join() and specify a delimiter (such as a comma, newline, tab, etc…).
- Loop through the items and add them to a StringBuilder.
I’ll show examples of both approaches.
Using String.Join()
String.Join() is the simplest way to convert a List to a string. With this method, you pass in the List and a delimiter and it outputs a string. You can use any delimiter you want. Here’s an example of converting a List to a comma-separated string (by passing in “,” as the delimiter):
var list = new List<string>()
{
"Bob", "Linda", "Tina", "Gene", "Louise"
};
string names = String.Join(",", list);
Console.WriteLine(names);
Code language: C# (cs)
This outputs the following comma-separated string (notice there’s no trailing comma):
Bob,Linda,Tina,Gene,Louise
Code language: plaintext (plaintext)
String.Join() can convert lists of any type. Internally, it calls ToString() to convert each item to a string. Here’s an example of converting a List of integers to a newline-separated string:
var list = new List<int>()
{
1,2,3,4,5
};
string names = String.Join(Environment.NewLine, list);
Console.WriteLine(names);
Code language: C# (cs)
Read more about the reverse option: converting a string to a list of integers.
This outputs the newline-separated string of integers:
1
2
3
4
5
Code language: plaintext (plaintext)
Using StringBuilder and a foreach loop
You can convert a List to a string with a foreach loop and StringBuilder.
- For each item, add the item and a delimiter with StringBuilder.Append().
- Trim off the trailing delimiter at the end with StringBuilder.Remove().
- Get the string with StringBuilder.ToString().
The following example shows how to do this. This converts a List of objects to a comma-separated string with a loop and StringBuilder:
using System.Text;
var list = new List<Person>()
{
new Person { Name = "Bob" },
new Person { Name = "Linda" },
new Person { Name = "Teddy" }
};
var sb = new StringBuilder();
var delimiter = ",";
foreach(var person in list)
{
sb.Append(person.Name);
sb.Append(delimiter);
}
//Remove the trailing delimiter
if (sb.Length > 0)
sb.Remove(sb.Length - 1, 1);
var names = sb.ToString();
Console.WriteLine(names);
Code language: C# (cs)
This creates a CSV string. Read more about parsing CSV strings.
This outputs the following comma-separated string of names:
Bob,Linda,Teddy
Code language: plaintext (plaintext)
Notice that there’s no trailing comma. It was removed after the loop with StringBuilder.Remove(). This is more efficient than conditionally adding the delimiter within the loop.