Using LINQ to convert a list to a CSV string

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

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 );

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);

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

String.Join(", ", list); //in .NET 4.0

and

String.Join(", ", list        
    .Select(i => i.ToString()).ToArray()) //in .NET 3.5 and below

Need Your Help

What's the 'Ruby way' to iterate over two arrays at once

ruby arrays iterator

More of a syntax curiosity than a problem to solve...

Is is possible to set a default PDO fetch mode?

php pdo

Before I retrieve data I always have to type: