C# Convert List to String with Comma Delimiter | Examples
A List
stores a collection of elements of the same type, which can be either inbuilt or custom-type classes.
The list is a data structure that stores elements in insertion order, and the elements are not sorted.
This tutorial explains how to convert a List
of Strings
into a string separated by a delimiter, such as a comma.
How to Convert a List of Strings into a Comma-Delimited String
There are multiple ways to convert a List into a comma-separated string.
You can create the list using the IList
or IEnumerable
interface
IList<string> numbers = new List<string>{"one","two","three"}; // .NET 4 version
IEnumerable<string> strEnumerable= new List<string>{"one","two","three"}; // Less than .NET 4 Version
- Using string.Join Method
The string.Join
method takes a separator and an enumerable object, such as a List, and returns a string of separator-delimited strings.
public static string Join<T>(string separator, IEnumerable<T> values)
Here is an example
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
IList<string> numbers = new List<string>{"one","two","three"};
string str = string.Join(",", numbers);
Console.WriteLine(str); // one two three
}
}
The same method works with IEnumerables:
IEnumerable<string> strEnumerable= new List<string>{"one","two","three"};
string str1 = string.Join(",", strEnumerable);
Console.WriteLine(str1); // one two three
}
- Using StringBuilder AppendJoin Method The
AppendJoin()
method in StringBuilder takes a separator and aList
, returning a comma-separated string.
using System;
using System.Collections.Generic;
using System.Text;
public class Program {
public static void Main() {
IList<string> numbers = new List<string>{"one","two","three"};
string str = string.Join(",", numbers);
var result= new StringBuilder().AppendJoin(", ", numbers).ToString();
Console.WriteLine(result); // one two three
}
}
Both of the above methods work with both IList and IEnumerable.