Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# one liner for .ToString() across entire array

Tags:

c#

shortcut

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;
    }
like image 519
user106795 Avatar asked Nov 29 '22 07:11

user106795


2 Answers

How about an extension method?

public static string[] ToStringArray<T>(this IEnumerable<T> items)
{
    return items.Select(i => i.ToString()).ToArray();
}
like image 145
Matt Hamilton Avatar answered Dec 05 '22 11:12

Matt Hamilton


Using LINQ:

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

string[] strings = ints.Select(i => i.ToString()).ToArray();
like image 42
Nick Farina Avatar answered Dec 05 '22 11:12

Nick Farina