Conversion for loop using lambda (C # 3.0)

How to convert below code

double sumxy = 0;

for (int i = 0; i < x.Count; i++)
{sumxy = sumxy + (x[i] * y[i]);}

      

using lambda

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

thanks

+2


a source to share


3 answers


If you are using .NET 4 you can use the operator Zip

:

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();

      

+7


a source


It doesn't really make sense, but if you want:



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

      

+3


a source


Something like that...

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

      

0


a source







All Articles