34

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();
}
0

3 Answers 3

90
int[] intarray = { 1, 2, 3, 4, 5 };
string[] result = intarray.Select(x=>x.ToString()).ToArray();
Sign up to request clarification or add additional context in comments.

3 Comments

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?
You are absolutely right. Looping is done by Select method.
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.
15

Try Array.ConvertAll

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

string[] result = Array.ConvertAll(myInts, x=>x.ToString());

1 Comment

Way to do it without "using System.Data.Linq;" which was requested but is a bigger hammer than is really needed.
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();

7 Comments

String.Join is not required.
Select is Linq method, defined in Enumerable class. ConvertAll is defined in Array class (that exists even before linq).
that means no need to declare using System.Linq; if we are using CovertAll! thank you so much!
That means you can use this in .Net 2.0 also..@InfantProgrammer'Aravind'
That is because .net3/3.5 are just additional libraries on .NET 2.0 core.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.