Reputation: 2041
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
Upvotes: 88
Views: 123499
Reputation: 41
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 a list of string to comma separated string C#.
Upvotes: 3
Reputation: 18799
To expand on Jon Skeets answer the code for this in .Net 4
is:
string myCommaSeperatedString = string.Join(",",ls);
Upvotes: 20
Reputation: 462
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()));
Upvotes: 4
Reputation: 8166
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);
Upvotes: 15
Reputation: 1500215
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.
Upvotes: 125
Reputation: 4535
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)?
Upvotes: 0