Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<long> to comma delimited string in C#

Tags:

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?

like image 519
John Shedletsky Avatar asked Dec 02 '10 00:12

John Shedletsky


People also ask

How do you convert a list to a comma separated String?

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.

How to convert list long to comma separated String in c#?

A List of string can be converted to a comma separated string using built in string. Join extension method. string. Join("," , list);

How do you add comma separated values in an array?

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.


1 Answers

string.Join is your friend...

var list = new List<long> {1, 2, 3, 4};
var commaSeparated = string.Join(",", list);
like image 70
James Kovacs Avatar answered Oct 26 '22 13:10

James Kovacs