In this post i want to talk about lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator =>, which is read as "goes to". In other words, lambda expression can be broken down into parameters followed by execution code:
Parameter => executioncode.
The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block. The lambda expression x=> x * x is read " x goes to x times x". In other words we want to square any given number and to do this we are going to assign to a delegate type as follows:
Result: The square of 5 is 25.
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas can be used in method-based LINQ queries as arguments to standard query operator methods such as Where. Let us look at the following pratical example:
I have my object Person that i can model into a list of anything that represents a person, for instance, in this case i have modeled it to give me a list of Students. Now that we have our Students, we can go ahead and filter the Students by their Age, in this example i want to return teenagers or independents.
Both "getTeenagers()" and "getIndependents()" uses a lambda expression as a predicate to compare each Student's Age and return a new collection of Students in their respective Age group.
For more on Lambda expressions you can read this article.
No comments:
Post a Comment