2

I'm in the process of trying to teach myself lambda expressions in C# and I've seem to have stumped myself...

This is essentially what I am trying to accomplish, please assume that ar1 & ar2 will always have the same length.

    double sum = 0;

    for(int x=0; x<size; x++){
        sum += (ar1[x]*ar2[x]);
    }

Notice the Arrays are being multiplied.

Is there an Lambda function that can accomplish this in a single line?

Thank you

1
  • 2
    Suppose you had to invent a method that took a lambda and two sequences; could you write such a method? Commented Jan 7, 2017 at 2:58

1 Answer 1

6
double sum = ar1.Zip(ar2, (a1, a2) => a1 * a2).Sum();

Zip - applies lambda to corresponding elements of two sequences

Sum - computes sum of results

Sign up to request clarification or add additional context in comments.

6 Comments

I mean it works -- can walk me through "ar1.zip(ar2, (a1, a2) +> a1*a2)"? .... pretend Im a total noob and have no idea what's going on (pretend)...
@Nefariis well, what Zip does - it gets enumerators of both sequences and starts enumerating them simultaneously. I.e. each time it calls MoveNext on both sequences. On each step we have two Current values (a1 and a2). And on each step Zip applies lambda function which accepts these two current values and produces some result. In our case lambda produces multiplication of two Current values. Result of multiplication is yielded. So actually Zip produces sequence of multiplications of corresponding items.
wait, I think Im seeing it -- you are creating another array with a1 and a2 zipped. Then saying that the indices (a1,a2) will be multiplied => a1*a2 - and then you are just summing it up at the end... Clever - here I was trying to iterate through each one
Thank you very much, I have a feeling this will come in handy
Linq is divine ;-)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.