35

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

0

4 Answers 4

115

In .NET 2/3

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

or (in .NET 4.0)

var csv = string.Join( ", ", list );
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn’t work if list is a list of integers as specified in the question.
@Timwi - actually, it does in .NET 4, though, I forgot the fact that you no longer need an array, any enumerable will work.
4

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

5 Comments

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
@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.
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.
@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"
@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.
2
string csv = String.Join(", ", list.Select(i=> i.ToString()).ToArray());

1 Comment

Technically, this answer does not produce the expected output as specified in the question ;-)
0
String.Join(", ", list); //in .NET 4.0

and

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

2 Comments

your second statement makes no sense. it will give you a string array with one element.
@Scott had an extra parantheses from my testing, fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.