335

It's a simple question; I am a newbie in C#, how can I perform the following

  • I want to convert an array of integers to a comma-separated string.

I have

int[] arr = new int[5] {1,2,3,4,5};

I want to convert it to one string

string => "1,2,3,4,5"
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223

5 Answers5

647
var result = string.Join(",", arr);

This uses the following overload of string.Join:

public static string Join<T>(string separator, IEnumerable<T> values);
Gibron
  • 1,350
  • 1
  • 9
  • 28
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
151

.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))
leppie
  • 115,091
  • 17
  • 196
  • 297
  • 19
    Thanks for the pre-.NET4 version! – kdenney Dec 15 '11 at 17:50
  • 1
    just realized i couldn't use the .net 4 version and i didn't understood why i was having an error until i saw your answer , thanks. – Luis Tellez May 21 '13 at 21:17
  • I am using .NET 4.5. I tried to concat the comma separated numbers with a string. I got an error saying "cannot convert string[] to char". So the earlier version worked flawlessly. – Prasanth G Jan 30 '20 at 12:49
16
int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);
AlanT
  • 3,627
  • 20
  • 28
Manish Nayak
  • 635
  • 9
  • 18
7

You can have a pair of extension methods to make this task easier:

public static string ToDelimitedString<T>(this IEnumerable<T> lst, string separator = ", ")
{
    return lst.ToDelimitedString(p => p, separator);
}

public static string ToDelimitedString<S, T>(this IEnumerable<S> lst, Func<S, T> selector, 
                                             string separator = ", ")
{
    return string.Join(separator, lst.Select(selector));
}

So now just:

new int[] { 1, 2, 3, 4, 5 }.ToDelimitedString();
nawfal
  • 70,104
  • 56
  • 326
  • 368
3

Use LINQ Aggregate method to convert array of integers to a comma separated string

var intArray = new []{1,2,3,4};
string concatedString = intArray.Aggregate((a, b) =>Convert.ToString(a) + "," +Convert.ToString( b));
Response.Write(concatedString);

output will be

1,2,3,4

This is one of the solution you can use if you have not .net 4 installed.

Guido Preite
  • 14,905
  • 4
  • 36
  • 65
sushil pandey
  • 752
  • 10
  • 9
  • 2
    It performs poorly due to the string concatenation, though – Simon Belanger Aug 18 '13 at 15:04
  • yes it will perform poorly but before .net 4.0 String.join only take string array as parameter.Thus in that case we also need to convert in string .we can use ToString it perform better but there is problem of null exception – sushil pandey Aug 20 '13 at 17:54