Categories
arrays c# string

Convert array of integers to comma-separated string

327

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"

    633

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

    This uses the following overload of string.Join:

    public static string Join<T>(string separator, IEnumerable<T> values);
    

    4

    • You do not need to pass the explicit generic argument in this case. It will be inferred.

      – leppie

      Jan 21, 2011 at 7:59

    • 7

      Pre .NET 4 string.Join(“,”, Array.ConvertAll(arr, i => i.ToString()))

      – TPAKTOPA

      Dec 12, 2014 at 14:06


    • Is there a simple way to do the reverse of this? Take the string and put it into an array?

      – Kory

      Mar 11, 2015 at 15:13

    • 4

      @Kory: Using String.Split method, see msdn.microsoft.com/en-us/library/…

      Mar 12, 2015 at 6:11

    148

    .NET 4

    string.Join(",", arr)
    

    .NET earlier

    string.Join(",", Array.ConvertAll(arr, x => x.ToString()))
    

    3

    • 19

      Thanks for the pre-.NET4 version!

      – kdenney

      Dec 15, 2011 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.

      May 21, 2013 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.

      Jan 30, 2020 at 12:49

    15

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