Performing function on each array element, returning results to new array
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.
Dan
Updated on June 30, 2022Comments
-
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 almost 11 yearsAh, how on earth did I miss this? Thanks! :)
-
Teejay almost 11 yearsDidn't know about
Select
, always usedToList().ConvertAll()
. Thanks!