34

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
  • 98,240
  • 88
  • 296
  • 433
lancscoder
  • 8,658
  • 8
  • 48
  • 68

4 Answers4

114

In .NET 2/3

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

or (in .NET 4.0)

var csv = string.Join( ", ", list );
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Doesn’t work if `list` is a list of integers as specified in the question. – Timwi Aug 12 '10 at 14:11
  • @Timwi - actually, it does in .NET 4, though, I forgot the fact that you no longer need an array, any enumerable will work. – tvanfosson Aug 12 '10 at 14:20
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);
Timwi
  • 65,159
  • 33
  • 165
  • 230
  • 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 Aug 12 '10 at 14:14
  • @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`, it would still be wrong). It’s an extension method. – Timwi Aug 12 '10 at 14:17
  • Actually, even the select as string isn't necessary as `Join( string, IEnumerable )` will automatically convert each item in the enumerable to a string. – tvanfosson Aug 12 '10 at 14:18
  • @Timwi: Yes, I mean `IEnumerable` - 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` See http://msdn.microsoft.com/en-us/library/bb548891.aspx "Enumerable Methods" – abatishchev Aug 12 '10 at 14:22
  • @abatishchev: I know all that. But there’s an important difference between `IEnumerable` and `IEnumerable` and there’s an important difference between *“a method of `IEnumerable`”* (your wording) and an extension method. – Timwi Aug 12 '10 at 14:23
2
string csv = String.Join(", ", list.Select(i=> i.ToString()).ToArray());
James Curran
  • 101,701
  • 37
  • 181
  • 258
  • Technically, this answer does not produce the expected output as specified in the question ;-) – Timwi Aug 12 '10 at 14:13
0
String.Join(", ", list); //in .NET 4.0

and

String.Join(", ", list        
    .Select(i => i.ToString()).ToArray()) //in .NET 3.5 and below
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142