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
abatishchev
101k88 gold badges303 silver badges443 bronze badges
asked Aug 12, 2010 at 14:08
4 Answers 4
In .NET 2/3
var csv = string.Join( ", ", list.Select( i => i.ToString() ).ToArray() );
or (in .NET 4.0)
var csv = string.Join( ", ", list );
answered Aug 12, 2010 at 14:10
2 Comments
Timwi
Doesn’t work if
list
is a list of integers as specified in the question.tvanfosson
@Timwi - actually, it does in .NET 4, though, I forgot the fact that you no longer need an array, any enumerable will work.
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);
answered Aug 12, 2010 at 14:10
5 Comments
abatishchev
In fact, list should be
IEnumerable
because all other containers (you mentioned and not only they) inherits IEnumerable
and Select
is a method of IEnumerable
Timwi
@abatishchev: The other containers implement
IEnumerable
, 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.tvanfosson
Actually, even the select as string isn't necessary as
Join<T>( string, IEnumerable<T> )
will automatically convert each item in the enumerable to a string.abatishchev
@Timwi: Yes, I mean
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"Timwi
@abatishchev: I know all that. But there’s an important difference between
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());
answered Aug 12, 2010 at 14:10
1 Comment
Timwi
Technically, this answer does not produce the expected output as specified in the question ;-)
String.Join(", ", list); //in .NET 4.0
and
String.Join(", ", list
.Select(i => i.ToString()).ToArray()) //in .NET 3.5 and below
answered Aug 12, 2010 at 14:12
2 Comments
Scott M.
your second statement makes no sense. it will give you a string array with one element.
Yuriy Faktorovich
@Scott had an extra parantheses from my testing, fixed.
lang-cs