Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert `List<string>` to comma-separated string

Tags:

c#

asp.net

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

like image 353
Ozkan Avatar asked Dec 21 '11 16:12

Ozkan


People also ask

How do you convert a list to a string separated by comma in 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.

How do you turn a column of data into a comma separated list?

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.)

How do you add a comma separated string to a list in Java?

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.

How can I convert comma separated string into a list string C#?

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.


2 Answers

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.

like image 185
Jon Skeet Avatar answered Sep 16 '22 20:09

Jon Skeet


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);

like image 41
Anthony Shaw Avatar answered Sep 20 '22 20:09

Anthony Shaw