Convert for loop by using lambda(C#3.0)
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]);
精彩评论