tags:

views:

251

answers:

4

I feel stupid for asking, but there must be a one liner that does the equivalent or near equivalent of the code below in c#... so can you tell me what it is?

    public static string[] ToStringArray(int[] i)
    {
        if (i==null) return null;
        string[] result = new string[i.Length];
        for (int n= 0; n< result.Length; n++)
            result[n] = i[n].ToString();
        return result;
    }
+10  A: 

How about an extension method?

public static string[] ToStringArray<T>(this IEnumerable<T> items)
{
    return items.Select(i => i.ToString()).ToArray();
}
Matt Hamilton
An extension method would work, but why not use the .Net frameworks ".Join" function for this?
RSolberg
See my comments on your answer. String.Join turns an array of strings into a single string. The original question called for a way to turn an array of ints into an array of strings.
Matt Hamilton
I missed the whole "int" part of that :)
RSolberg
I think an extension method would probably look a bit better in the code in the long run then.
RSolberg
egads, it even works in the watch window: (new int[] { 1,2,3,4,5}).ToStringArray()
+9  A: 

Using LINQ:

int[] ints = { 1, 2, 3 };

string[] strings = ints.Select(i => i.ToString()).ToArray();
Nick Farina
+2  A: 

Using LINQ:

(from x in i select x.ToString()).ToArray()
Kevin Gadd
+1  A: 

int[] x = new int[] {1,2,3};
string[] y = Array.ConvertAll(x, intArg => intArg.ToString());

shahkalpesh