Performing function on each array element, returning results to new array

13,136

Solution 1

You can use Select() to transform one sequence into another one, and ToArray() to create an array from the result:

int[] numbers = { 1, 2, 3 };
string[] strings = numbers.Select(x => ToWords(x)).ToArray();

Solution 2

It's pretty straight forward. Just use the Select method:

var results = array.Select(ToWords).ToArray();

Note that unless you need an array you don't have to call ToArray. Most of the time you can use lazy evaluation on an IEnumerable<string> just as easily.

Share:
13,136
Dan
Author by

Dan

Updated on June 30, 2022

Comments

  • Dan
    Dan almost 2 years

    I'm a complete Linq newbie here, so forgive me for a probably quite simple question.

    I want to perform an operation on every element in an array, and return the result of each of these operations to a new array.

    For example, say I have an array or numbers and a function ToWords() that converts the numbers to their word equivalents, I want to be able to pass in the numbers array, perform the ToWords() operation on each element, and pass out a string[]

    I know it's entirely possible in a slightly more verbose way, but in my Linq adventures I'm wondering if it's doable in a nice one-liner.

  • Dan
    Dan almost 11 years
    Ah, how on earth did I miss this? Thanks! :)
  • Teejay
    Teejay almost 11 years
    Didn't know about Select, always used ToList().ConvertAll(). Thanks!