Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ to convert a list to a CSV string

Tags:

c#

csv

linq

I have a list of integers and I want to be able to convert this to a string where each number is separated by a comma.

So far example if my list was:

1 2 3 4 5 

My expected output would be:

1, 2, 3, 4, 5 

Is this possible using LINQ?

Thanks

like image 262
lancscoder Avatar asked Aug 12 '10 14:08

lancscoder


People also ask

How to convert List 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 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 do you convert a List to a comma separated string in python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].

What does string Join do C#?

In C#, Join() is a string method. This method is used to concatenates the members of a collection or the elements of the specified array, using the specified separator between each member or element. This method can be overloaded by passing different parameters to it.


2 Answers

In .NET 2/3

var csv = string.Join( ", ", list.Select( i => i.ToString() ).ToArray() ); 

or (in .NET 4.0)

var csv = string.Join( ", ", list ); 
like image 192
tvanfosson Avatar answered Sep 29 '22 03:09

tvanfosson


Is this what you’re looking for?

// Can be int[], List<int>, IEnumerable<int>, ... int[] myIntegerList = ...;  string myCSV = string.Join(", ", myIntegerList.Select(i => i.ToString()).ToArray()); 

Starting with C# 4.0, the extra mumbojumbo is no longer necessary, it all works automatically:

// Can be int[], List<int>, IEnumerable<int>, ... int[] myIntegerList = ...;  string myCSV = string.Join(", ", myIntegerList); 
like image 31
Timwi Avatar answered Sep 29 '22 04:09

Timwi