This often comes up. I have a List and I want to go to a comma delimited string of all the elements in the list that I can use in SQL.
What is the most elegant way to do this in C#? Iterating over all of them is fine, except either the first or last element has to be special-cased since I don't want leading or trailing commas.
Got a good one-liner?
Approach: This can be achieved with the help of join() method of String as follows. Get the List of String. Form a comma separated String from the List of String using join() method by passing comma ', ' and the list as parameters. Print the String.
A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);
The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.
string.Join is your friend...
var list = new List<long> {1, 2, 3, 4};
var commaSeparated = string.Join(",", list);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With