What is the difference between "lambda" and LINQ? How to differentiate them in a sentence?

21

I often see terms like LINQ query and lambda expressions .

Then the question came up, What I'm doing is a LINQ query, a lambda expression, or both?

Ex1:

var query = Produtos.Where(p => p.Descr.StartsWith("A")).Take(10);

Ex2:

var query = from produto in Produtos.Take(10)
where produto.Descr.StartsWith("A")
select new Produto 
{ Id = produto.Id, Descr = produto.Descr};
    
asked by anonymous 09.08.2015 / 04:07

2 answers

18

LINQ is one thing and has two different syntaxes:

  • one is the query syntax or declarative form and many people think that this is just LINQ (their second example)
  • Another is the method or imperative form syntax that many people think is a lambda (their first example)

It is already clear that the two forms are LINQ, one in more natural language and one more similar to what we normally program. The second form usually uses lambda , to represent the codes needed to execute the expression. Although we can understand this, we can not simply call this lambda since this is just a mechanism used to form the entire LINQ expression. It is worth remembering that the more declarative form also uses lambda , but in a more disguised way being code passed by clause rather than method argument as in imperative form.

Differentiation occurs by the way it is written. The declarative form looks like the programming language, it is a more natural reading. The imperative way is to use the raw methods full of dots, parentheses and notation of receipt of lambda parameters.

To learn more, to understand the benefits of each form, I have already answered this .

09.08.2015 / 04:29
7

LINQ uses lambdas , but lambdas can be used without LINQ as well. Example:

//declara uma função que retorna um bool, para ver se um int tem todos os mesmos números
public static bool TodosIguais( this int num, Func<T,bool> igual ) {
  return igual(num);
}

//usa essa função, mas posso mandar qualquer função que retorna um bool
int numero = 55;

//Usando um lambda mais complexo:
bool todosIguais = numero.TodosIguais( i => {
    char comparar = num.ToString()[0];
    foreach( var n in num.ToString() ) {
      if ( comparar != n ) { return false; }
    }
    return true;
  } );

//Usando um lambda um pouco mais simples
todosIguais = numero.TodosIguais( 
  i => i.ToString().All(c=>c.Equals(i.ToString().First())) );

//Usando um lambda super simples, mas que possa retornar algo errado
todosIguais = numero.TodosIguais( i => i == i );

In other words, lambda is a succinct command to declare a function, being the function parameters before => , and the function content after.

    
10.05.2016 / 17:01