Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound Select using lambda expression

Tags:

c#

.net

lambda

linq

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 };
like image 373
Ahsan Iqbal Avatar asked Aug 25 '11 09:08

Ahsan Iqbal


People also ask

How do you declare a lambda function in C?

C# language specification. See also. You use a lambda expression to create an anonymous function. Use the lambda declaration operator => to separate the lambda's parameter list from its body. A lambda expression can be of any of the following two forms: Expression lambda that has an expression as its body: C#.

How do you create a lambda expression?

Expression lambda that has an expression as its body: Statement lambda that has a statement block as its body: To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator and an expression or a statement block on the other side.

How do I separate the parameter list from the lambda expression?

Use the lambda declaration operator => to separate the lambda's parameter list from its body. A lambda expression can be of any of the following two forms: Expression lambda that has an expression as its body: Statement lambda that has a statement block as its body:

How do you make a Lambda statement block?

Statement lambda that has a statement block as its body: To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator and an expression or a statement block on the other side. Any lambda expression can be converted to a delegate type.


1 Answers

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.

like image 92
Martin Liversage Avatar answered Oct 19 '22 23:10

Martin Liversage