In today’s section we’ll see how to use extension methods to achieve the same thing which can be achieved via Comprehension LINQ query.
Below is the code to fetch the same thing via two ways.
I have also created Movies Repository, just to segregate my stuffs here. So, GetMovies() is just fetching all the movies from the repository.
so, now at this point you might be thinking that what i should be using Extension Method or comprehension query. Basically, its a personal choice. If users feel handy with comprehension query, they write comprehension query otherwise extension methods. However, my point is extension methods using lambda expressions generally offer more flexibility over comprehension queries and the general reason for that not all LINQ keywords are exposed to comprehension queries. So, when you are writing extension methods then in that case select operator is optional.
Now, lets see let keyword. let keyword is really important in LINQ queries for persisting some value for later execution like shown below
here, in the movies repository i have modified the name just to execute the query, but that ok that was just done to prove the point. Now, there is one more keyword which is used for grouping or i would say for additional filtering like the example shown below.
below in the snippet i have used group operator to partition my results as shown below.
I have also modified Movie class and Movie Repository
Now, lets suppose you would like to print some additional information like for a particular Genre Id, total count and its collection. So, to do that i’ll extend the query with anonymous syntax as shown below.
Now, lets look at Join query.
for this i have also created one new MovieReview Repo as shown below in the snippet.
so, when i run the same, i will get the below result
I can also go ahead and use LINQ composition like shown below.
For this custom type, i have created the same in my movie repository as shown below in the snippet
Now, when i run the same, it will produce me the below output.
Now, this kind of query is very useful as it increases reusability of the code.
Thanks for joining me.
3,157 total views, no views today