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
To expand on Jon Skeets answer the code for this in .Net 4
is:
string myCommaSeperatedString = string.Join(",",ls);
That's the way I'd prefer to see if I was maintaining your code. If you manage to find a faster solution, it's going to be very esoteric, and you should really bury it inside of a method that describes what it does.
(does it still work without the ToArray)?
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()));
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);
}
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);
Source: Stackoverflow.com