2

I know have this simple lambda query(not sure if this one called a query)

var person = db.People.Where(a => a.PersonId == id).FirstOrDefault();

I have a question because i don't know anything about lambda. What is the purpose of => and what is the value of that in linq if it is converted to linq?.

For my basic knowledge this might the converted linq query

var person = (from p in db.Person where p.PersonId == id select p).FirstOrDefault();

right?

  • 3
    Possible duplicate of [What does the '=>' syntax in C# mean?](http://stackoverflow.com/questions/290061/what-does-the-syntax-in-c-sharp-mean) – Gilad Green Aug 31 '16 at 07:07
  • 3
    Both are linq. The top is called method syntax while the bottom is called query syntax – Gilad Green Aug 31 '16 at 07:08

3 Answers3

1

The =>, which can be read as maps to or is mapped to belongs to the syntax of labda expressions. Informally the syntax of lambda expressions is

(arg_1, arg_2, ..., arg_n) => rhs,

where (arg-1, arg_2, ..., arg_n) is the list of arguments; if there is one argument, the list (arg1) can be abbreviated to arg1. rhs is either an expression of the desired return type, such as in

x => x * x

or a compound statement returning the desired type as follows.

x =>
{
    return x * x;
}

The arguments and return type of the lambda expression are not explicitly defined but deduced at compile time. In total,

a => a.PersonId == id

defines function which maps a person a to a boolean value which is generated by evaluating a.PersonId == id, which means that the return value is true if and only if the person's PersonId is equal to id.

Codor
  • 17,447
  • 9
  • 29
  • 56
0

The => is the lambda operator, and is part of the syntax for lambda expressions.

On the left of the => are the input parameters for the expression on the right of =>

a=> a.PersonId == id

is like a function that takes a person object and an Id and returns a boolean, i.e.

bool CheckIfIdIsEqual(Person a, int id) {
     return a.PersonId == id;
}
robor
  • 2,969
  • 2
  • 31
  • 48
0

Yes, you are right. The expressions where we use => operator are called lambda expressions.

In the lambda calculus, we describe these patterns as tiny functions. In the C# language, we use lambda functions and the => operator to transform data.

 var person = db.People.Where(a => a.PersonId == id).FirstOrDefault();

In the above code, we access all the values or data from db.People using the variable a

For more information you can refer:

1.Expression Lambdas

2.C Sharp Lambda Expression

3.Lambda Expression

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Jibin Balachandran
  • 3,381
  • 1
  • 24
  • 38