Reputation: 58804
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
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
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