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();
return stringArray.Select(s => Convert.ToInt32(s)).ToArray();
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With