Convert List <string> to Comma Separated String

Is there a quick way to convert List<string> to comma-separated string in C #?

I do it this way, 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: Search on this site, but most Java or Python solutions

+61
Dec 21 '11 at 16:40
source share
6 answers

In .NET 4, you don't need a ToArray() call - string.Join overloaded to accept IEnumerable<T> or just IEnumerable<string> .

There are potentially more efficient ways to do this before .NET 4, but do you really need them? Is this really a bottleneck in your code?

You can iterate through the list, work out the final size, select the StringBuilder exactly the right size, and then make the connection yourself. This will avoid creating an additional array for some reason - but it will not save much time, and it will be much more code.

+98
Dec 21 2018-11-21T00:
source share

The following is a comma separated list. Remember to include the 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 give one, two

if you need a space after the decimal point, just change the last line to string type = ls.Aggregate((x,y) => x + ", " + y);

+13
Dec 21 '11 at 16:54
source share

To deploy the answer to Jon Skeets, the code for this in .Net 4 is:

 string myCommaSeperatedString = string.Join(",",ls); 
+8
Jun 19 '15 at 7:48
source share

Follow this:

  List<string> name = new List<string>(); name.Add("Latif"); name.Add("Ram"); name.Add("Adam"); string nameOfString = (string.Join(",", name.Select(x => x.ToString()).ToArray())); 
+3
Apr 11 '15 at 7:04 on
source share

The way I prefer to see if I support your code. If you can find a quicker solution, it will be very esoteric, and you must really bury it inside the method that describes what it does.

(does it work without ToArray)?

0
Dec 21 2018-11-21T00:
source share
 static void Main(string[] args) { List<string> listStrings = new List<string>(){ "C#", "Asp.Net", "SQL Server", "PHP", "Angular"}; string CommaSeparateString = GenerateCommaSeparateStringFromList(listStrings); Console.Write(CommaSeparateString); Console.ReadKey(); } private static string GenerateCommaSeparateStringFromList(List<string> listStrings) { return String.Join(",", listStrings); } 

Convert string list to C # comma string.

0
Jun 17 '17 at 11:29 on
source share



All Articles