Convert `List<string>` to comma-separated string
C#asp.netC# Problem Overview
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
C# Solutions
Solution 1 - C#
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.
Solution 2 - C#
To expand on Jon Skeets answer the code for this in .Net 4
is:
string myCommaSeperatedString = string.Join(",",ls);
Solution 3 - C#
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);
Solution 4 - C#
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()));
Solution 5 - C#
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);
}
Solution 6 - C#
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)?