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
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.
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);
To deploy the answer to Jon Skeets, the code for this in .Net 4 is:
string myCommaSeperatedString = string.Join(",",ls); 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())); 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)?
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); }