Andrew Grant
Andrew Grant

Reputation: 58804

Elegant way to transform arrays in C#?

Is there a nice LINQ (or other) method of creating a new array by performing a transformation on each element of an existing array?

E.g. an alternative to:

List<int> numbers = new List<int>();
foreach(string digit in stringArray)
{
  numbers.Add(Convert.ToInt32(digit));
}
return numbers.ToArray();

Upvotes: 6

Views: 6489

Answers (3)

Adam Maras
Adam Maras

Reputation: 26863

Something like this?

int[] numbers = stringArray.Select(s => Convert.ToInt32(s)).ToArray();

Or, with query syntax:

int[] numbers = (from s in stringArray
                 select Convert.ToInt32(s)).ToArray();

Upvotes: 9

BFree
BFree

Reputation: 103760

return stringArray.Select(s => Convert.ToInt32(s)).ToArray();

Upvotes: 10

Donut
Donut

Reputation: 112875

Yep! LINQ is perfectly suited to this sort of thing. Here's an example using query syntax:

return (from s in stringArray 
        select Convert.ToInt32(s)).ToArray();

BFree's answer is the method syntax equivalent. Here's an MSDN article on the difference between the two.

Upvotes: 5

Related Questions