user6472290
user6472290

Reputation:

Lambda - Linq Convert

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?

Upvotes: 2

Views: 162

Answers (3)

Jibin Balachandran
Jibin Balachandran

Reputation: 3441

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

Upvotes: 0

Codor
Codor

Reputation: 17595

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.

Upvotes: 1

robor
robor

Reputation: 3089

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;
}

Upvotes: 0

Related Questions