Is there a fast way to convert List<string>
to a comma-separated string
in C#?
I do it like this but Maybe there is a faster or more efficient way?
List<string> ls = new List<string>();
ls.Add("one");
ls.Add("two");
string type = string.Join(",", ls.ToArray());
PS: Searched on this site but most solutions are for Java or Python
Best Answer
In .NET 4 you don't need the
ToArray()
call -string.Join
is overloaded to acceptIEnumerable<T>
or justIEnumerable<string>
.There are potentially more efficient ways of doing it before .NET 4, but do you really need them? Is this actually a bottleneck in your code?
You could iterate over the list, work out the final size, allocate a
StringBuilder
of exactly the right size, then do the join yourself. That would avoid the extra array being built for little reason - but it wouldn't save much time and it would be a lot more code.