32

When I am converting array of integers to array of string, I am doing it in a lengthier way using a for loop, like mentioned in sample code below. Is there a shorthand for this?

The existing question and answers in SO are about int[] to string (not string[]). So they weren't helpful.

While I found this Converting an int array to a String array answer but the platform is Java not C#. Same method can't be implemented!

        int[] intarray =  { 198, 200, 354, 14, 540 };
        Array.Sort(intarray);
        string[] stringarray = { string.Empty, string.Empty, string.Empty, string.Empty, string.Empty};

        for (int i = 0; i < intarray.Length; i++)
        {
            stringarray[i] = intarray[i].ToString();
        }
Community
  • 1
  • 1
InfantPro'Aravind'
  • 11,692
  • 23
  • 79
  • 113

3 Answers3

84
int[] intarray = { 1, 2, 3, 4, 5 };
string[] result = intarray.Select(x=>x.ToString()).ToArray();
Tilak
  • 28,854
  • 17
  • 79
  • 129
  • 1
    Works! Let me try to understand the code. The looping is being done here isn't it? but not explicitly! Each number in intarray is converted to string (x=>x.ToString()). Am I correct here? – InfantPro'Aravind' Dec 27 '12 at 07:55
  • 1
    You are absolutely right. Looping is done by [Select](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.select.aspx) method. – Tilak Dec 27 '12 at 07:57
  • Please edit the question only if it is really necessary and try to make all possible editions at once. exceeding certain number of editions may turn post into wiki! Thanks. – InfantPro'Aravind' Jan 16 '13 at 10:08
14

Try Array.ConvertAll

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

string[] result = Array.ConvertAll(myInts, x=>x.ToString());
Rolwin Crasta
  • 4,061
  • 3
  • 32
  • 44
  • 3
    Way to do it without "using System.Data.Linq;" which was requested but is a bigger hammer than is really needed. – Task Nov 07 '14 at 20:57
5

Here you go:

Linq version:

String.Join(",", new List<int>(array).ConvertAll(i => i.ToString()).ToArray());

Simple one:

string[] stringArray = intArray.Select(i => i.ToString()).ToArray();
Vishal Suthar
  • 16,685
  • 2
  • 55
  • 101