Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to transform arrays in C#?

Tags:

c#

linq

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();
like image 683
Andrew Grant Avatar asked Nov 09 '10 20:11

Andrew Grant


3 Answers

return stringArray.Select(s => Convert.ToInt32(s)).ToArray();
like image 144
BFree Avatar answered Oct 20 '22 01:10

BFree


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();
like image 38
Adam Maras Avatar answered Oct 20 '22 00:10

Adam Maras


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.

like image 21
Donut Avatar answered Oct 19 '22 23:10

Donut