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
Use the join() Function to Convert a List to a Comma-Separated String in Python. The join() function combines the elements of an iterable and returns a string. We need to specify the character that will be used as the separator for the elements in the string.
Please follow these instructions: 1. Type the formula =CONCATENATE(TRANSPOSE(A1:A7)&",") in a blank cell adjacent to the list's initial data, for example, cell C1. (The column A1:A7 will be converted to a comma-serrated list, and the separator "," will be used to separate the list.)
Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.
To convert a delimited string to a sequence of strings in C#, you can use the String. Split() method. Since the Split() method returns a string array, you can convert it into a List using the ToList() method.
In .NET 4 you don't need the ToArray()
call - string.Join
is overloaded to accept IEnumerable<T>
or just IEnumerable<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.
The following will result in a comma separated list. Be sure to include a using statement for System.Linq
List<string> ls = new List<string>(); ls.Add("one"); ls.Add("two"); string type = ls.Aggregate((x,y) => x + "," + y);
will yield one,two
if you need a space after the comma, simply change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With