开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜