Lambda Expressions: Public Bool Return
Lambda Expressions: Public Bool Return
While you are working with LINQ, you will find some "weird syntax" in the form x => y. If you are not familiar with this
syntax, I will explain it shortly.
In each LINQ function you will need to define some condition that will be used to filter objects. The most natural way to do
this is to pass some function that will be evaluated, and if an object satisfies a condition defined in the function, it will be
included in the result set of the LINQ function. That kind of condition function will need to take an object and return a
true/false value that will tell LINQ whether or not this object should be included in the result set. An example of that kind of
function that checks if the book is cheap is shown in the following listing:
Hide Copy Code
If the book price is less than 10, it is cheap. Now when you have this condition, you can use it in the LINQ clause:
Hide Copy Code
In this code we have defined a "function pointer" to the function IsBookCheap in the form Func<Book, bool>, and this
function is passed to the LINQ query. LINQ will evaluate this function for each book object in the books collection and return
a book in the resulting enumeration if it satisfies the condition defined in the function.
This is not a common practice because conditions are more dynamic and it is unlikely that you can create a set of
precompiled functions somewhere in the code, and they will be used by all LINQ