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
In .NET 2/3
var csv = string.Join( ", ", list.Select( i => i.ToString() ).ToArray() );
or (in .NET 4.0)
var csv = string.Join( ", ", list );
list is a list of integers as specified in the question.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);
IEnumerable because all other containers (you mentioned and not only they) inherits IEnumerable and Select is a method of IEnumerableIEnumerable, correct. The rest of what you said it wrong, especially the “list should be IEnumerable”, but also the “Select is a method of IEnumerable” (and even if you had said IEnumerable<T>, it would still be wrong). It’s an extension method.Join<T>( string, IEnumerable<T> ) will automatically convert each item in the enumerable to a string.IEnumerable<T> - omitted just for short. Extension methods can't be in the air, they should be linked to some class and Select is linked to IEnumerable<T> See msdn.microsoft.com/en-us/library/bb548891.aspx "Enumerable Methods"IEnumerable and IEnumerable<T> and there’s an important difference between “a method of IEnumerable” (your wording) and an extension method.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