C# How to Convert List to String in C#| C# Examples
List stores collection of elements of the same type. Types can be inbuilt or custom-type classes.
The list is a data structure that stores the elements in insertion order, Elements are not sorted.
This tutorial explains 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 delimiter String
Multiple ways we can convert List into comma separated String
The list can be created 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
-
use string.join method
string.join
method takes a separator and enumerable object such as 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 above method works with IEnumerables
IEnumerable<string> strEnumerable= new List<string>{"one","two","three"};
string str1 = string.Join(",", strEnumerable);
Console.WriteLine(str1); // one two three
}
- use the StringBuilder AppendJoin method
AppendJoin() method in StringBuilder takes
separator
andList
and returns 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
}
}
Above two methods works with IList
and IEnumerables