What you are looking for is most likely the static method Join from the string class. It is a very smooth way to create a comma separated string and you can easily separate it by any separator (delimiter) you wish. It can be used like below:
var someList = new List<string>
{
"A","B","C"
};
var commaSeparatedString = string.Join(",", someList);
//result will be "A,B,C"
If you want a space after each word you just add that to the first parameter of the Join:
var someList = new List<string>
{
"A","B","C"
};
var commaSeparatedString = someList.ToCommaSeperatedString();
//result will be "A,B,C"
As previously mentioned you can use any separator, here is an example with a dash -
:
var someList = new List<string>
{
"A","B","C"
};
var commaSeparatedString = string.Join("-", someList);
//result will be "A-B-C"
Using an extension method
If you need this in many places you can create a small extension method (ToCommaSeperatedString
). Using the Join
method is so simple to use that it might seem like overkill to create an extension method, but I will leave some examples here regardless. Below is an example on how to wrap the functionality of creating a comma separated string from a list of strings, in an extension method:
public static class StringExtentions
{
public static string ToCommaSeperatedString(this IEnumerable<string> list)
{
return string.Join(",", list);
}
}
And it can be used like below:
var someList = new List<string>
{
"A","B","C"
};
var commaSeparatedString = someList.ToCommaSeperatedString();
//result will be "A,B,C"
Alternatively you can provide the separator and make a ToSeperatedString
method:
public static class StringExtentions
{
public static string ToSeperatedString(this IEnumerable<string> list
, string separator)
{
return string.Join(separator, list);
}
}
And it can be used like below:
var someList = new List<string>
{
"A","B","C"
};
var commaSeparatedString = someList.ToSeperatedString(",");
//result will be "A,B,C"
That is all
That is an easy way to turn a list of strings into a comma separated string. Please leave a comment down below with your thoughts!