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 开发者_JAVA百科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
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
精彩评论