开发者

Elegant way to transform arrays in C#?

开发者 https://www.devze.com 2023-01-24 10:50 出处:网络
Is there a开发者_JS百科 nice LINQ (or other) method of creating a new array by performing a transformation on each element of an existing array?

Is there a开发者_JS百科 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号