9

What is equivalent of following code snippet in lambda expression?

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
    from a in numbersA
    from b in numbersB
    where a < b
    select new { a, b };
1
  • 1
    Just fired up ILSpy to find out, but it didn't change it into methods. (Looks like i'll have to wait for @Jon Skeet!) Commented Aug 25, 2011 at 9:44

1 Answer 1

10

Here is a LINQ expression using method syntax (as opposed to query syntax):

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

pairs = numbersA
  .SelectMany(_ => numbersB, (a, b) => new { a, b })
  .Where(x => x.a < x.b);

The original query is translated into this:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
int[] numbersB = { 1, 3, 5, 7, 8 }; 

pairs = numbersA
  .SelectMany(_ => numbersB, (a, b) => new { a, b })
  .Where(x => x.a < x.b)
  .Select(x => new { x.a, x.b });

However the last Select isn't required and can be removed.

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

4 Comments

+1, Is that actually what it's translated to, or is that just how you would do it?
@George Duckett: I have expanded my answer to answer your comment.
Thanks, out of interest, how did you find out the original translation?
I knew that having multiple from translates into SelectMany but I wasn't exactly sure about the last Select so I compated the generated IL and saw it was the same.

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.