开发者

Lambda expression syntax

开发者 https://www.devze.com 2023-02-12 11:40 出处:网络
Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?

Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?

In lambda expressions, the sign => is always used. What does it mean?

 cust开发者_如何学编程omers.Where(c => c.City == "London"); 

Here c => is used but why? What kind of meaning of using c =>. Please discuss in detail because I don't know lambda.


No, you don't have to use a lambda expression. For example, your Where example could be written as:

private static bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

...

var londoners = customers.Where(IsLondon);

That's assuming LINQ to Objects, of course. For LINQ to SQL etc, you'd need to build an expression tree.

As to why "=>" is always used in a lambda expression, that's simply because that's the way the operator is written - it's like asking why "+" is used for addition.

A lambda expression of "c => ..." is effectively giving the lambda expression a parameter called c... in this case generic type inference provides the type of c. The body provides either an action to perform or some calculation to return a value based on c.

A full-blown description of lambda expressions is beyond the scope of this answer. As a blatant plug for my book, however, they're covered in detail in chapter 9 of C# in Depth.


The lambda expression

c => c.City == "London"

is shorthand for something like

bool IsCustomerInLondon(Customer c)
{
  return (c.City == "London");
}

It's just a very concise way of writing a simple function that returns a value. It's called an "anonymous function" because it's never assigned a name or a formal definition (the parameter types and the return type are inferred from the context).

(Actually, it's not just shorthand; lambda expressions are related to some other constructs called closures, which are very cool and powerful tools.)


Think about lambdas as anonymous of functions. I'll try to explain it with following code.

public bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

Now we strip down function name and get rid of braces:

public bool Customer customer    
    return customer.City == "London";

We don't need return type, because compiler is able to deduce type from expression:

 customer.City == "London";

In the same manner compiler knows about input type, so we don't need to specify it.

So basically, what we left with is

customer
   return customer.City == "London";

And lambda syntax in c# is basically:

(parameter list) => "expression"

You can also write "multi-line" expressions, but then you have to surround your code with curly braces. Also you will need to use "return" statement, like you usually do.


Jon already answered, but I'd like to add this.

In the example you have given, imagine Linq looping over all customers, and c is simply a reference to each item in the enumerable:

var result = new List<Customer>();
foreach(var c in customers)
{
     if (c.City == "London")
        result.Add(c);   
}
return result;

It's a variable like any other, it does not have to be a single named one, but it's just a convention of some sort.


you do not need to use lambda expressions on Lİnq to sql or Entities; here is an alternative way of your code;

you code :

customers.Where(c => c.City == "London");

the other way;

  var query = from cs in customers
              where cs.City == "London"
              select cs;

this is the another way. it is up to you.


Lambda and linq are quite separate. You can use one without using the other (there are parts of linq that depend on lambda expressions, but we want to keep it simple :-) )

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

This was from MSDN. (http://msdn.microsoft.com/en-us/library/bb397687.aspx )

To make it short (it's much more complex) you can use a lambda expression to make a local function. what you put before the => (in your example the c) will be the parameter of the function. The return type is "discovered" by the C# compiler.

c => c.City == "London" is nearly equivalent to:

delegate (TheObjectTypeOfC c) {
   return c.City == London
};

(the difference is that some lambda expression are delegates and also expressions, but please ignore this, you won't need it for some time)

If/when the compiler isn't able to infer the types of the parameters, you can force them: (MyObject p) => p.SomeProperty != null. Here you are telling the compiler that p is a parameter.

While here I showed you what are called "expression lambdas", you can even do "statement lambdas":

p => {
   for (int i = 0; i < 10; i++) {
       if (p.SomeProperty == 0) {
          return true;
       }
   }

   return false;
}

(I won't tell you what are the "behind the scenes" differences between expression lambdas and statement lambdas. If you want to know them, read the msdn page I pointed before)


No it is not necessary at all.

We have two ways to write LINQ queries.

One is query method and other is builder method. You only need to put lambda expression in case of builder method. For example, if we want to find all those students from some Students object that have more marks than 70. but we can do this thing in LINQ with following syntax

   var data = from p in stdList
   where p.marks > 70
   select p;

or var data = stdList.Where(p=>p.marks > 70);

later approach is builder method, in Where function, we are passing lambda expressions.

Lambda expressions are just short cuts of doing things you can always use LINQ queries but if you want to avoid whole query syntax for just applying a simple condition you can just use LINQ builder methods (which asks for lambda expressions) in lambda expressions, you always define some alias and then perform your operation.

As far as => operator is concerned, It works just like assignment operator. For example:

(p) => p.Gender == “F”
It means  “All persons  p, such that person’s Gender is F”

In some literature this is called “predicate”. Another literature terminology is “Projection”

(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F”” 

This is projection, it uses ternary operator. Although i explained with very basic examples but i hope this would help you . . . :)

0

精彩评论

暂无评论...
验证码 换一张
取 消