Elegant way to convert arrays to C #?

Is there a good LINQ (or other) method for creating a new array by performing a conversion for each element of an existing array?

eg. alternative:

List<int> numbers = new List<int>(); foreach(string digit in stringArray) { numbers.Add(Convert.ToInt32(digit)); } return numbers.ToArray(); 
+4
source share
3 answers
 return stringArray.Select(s => Convert.ToInt32(s)).ToArray(); 
+8
source

Something like that?

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

Or with query syntax:

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

Oops! LINQ is great for this kind of thing. The following is an example of using query syntax :

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

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

+5
source

All Articles