开发者

Convert for loop by using lambda(C#3.0)

开发者 https://www.devze.com 2022-12-29 15:41 出处:网络
How to convert the below code double sumxy = 0; for (int i 开发者_如何学C= 0; i < x.Count; i++)

How to convert the below code

double sumxy = 0;

for (int i 开发者_如何学C= 0; i < x.Count; i++)
{sumxy = sumxy + (x[i] * y[i]);}

by using lambda

I am using C#3.0. x and y are list of double numbers

Thanks


If you're using .NET 4, you could use the Zip operator:

double sumxy = x.Zip(y, (a, b) => a * b).Sum();

Or in .NET 3.5:

double sumxy = x.Select((value, index) => value * y[index]).Sum();


There isn't really any point, but if you want to:

Enumerable.Range(0, x.Count).Select(i => x[i] * y[i]).Sum();


Something like this...

var sumy = Enumerable.Range(0, x.Count).Aggregate((result, i) => result + (x[i]*y[i]);
0

精彩评论

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

关注公众号