开发者

Convert two arrays to a new one using LINQ

I have two double[] X and double[] Y.

I want to create a new array Z, where each Zi = Xi * Yi

I wonder if it's possible to do w开发者_Python百科ith LINQ?

(I'm learning LINQ now; of course I can use plain for).


It's possible at 4.0, using Zip (that's the definition of zip - combining elements on the same position):

double[] Z = X.Zip(Y, (x, y) => x * y).ToArray();

On 3.5 you can use MoreLinq, which has a custom Zip extension method.


If you don't want to use a 3rd party lib or .NET 4.0, you could use 'Select'

double[] z = x.Select((d, i) => d * y[i]).ToArray();

'i' is the index of element 'd' for the current iteration and it's used here to retrieve the accordant element from y.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜