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();
}
The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
Rookie Programmer Aravind
  • 11,952
  • 23
  • 81
  • 114

3 Answers3

85
int[] intarray = { 1, 2, 3, 4, 5 };
string[] result = intarray.Select(x=>x.ToString()).ToArray();
Tilak
  • 30,108
  • 19
  • 83
  • 131
  • 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? – Rookie Programmer 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. – Rookie Programmer 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,219
  • 3
  • 35
  • 45
  • 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
  • 17,013
  • 3
  • 59
  • 105