I got my blogger hat on after a very long time. With all the
week end lectures and office works cramping up my schedule, there was virtually
no time left for me to blog about anything. I came across pretty interesting topics
and subjects over my past few non blogging months and will try to share them
with you in the coming days.
Ok let’s get started…
Let’s say we are writing a SQL query to retrieve the names
of the customers who are above 20, we will write something like this
select cust.name
from customers cust
where cust.age>20
But when it comes to LINQ, as we all know the syntax is
totally inverted.
The same query will look like this when we do it on a list
of Customer objects.
IEnumerable<string> olderCustomersQuery = from cust in
customers
where cust.Age > 20
select cust.Name;
But WHY!!!
To understand we need to get back to basics.
There are two ways to build up a LINQ expression,
Extension methods and Query operators. The one mentioned above falls in to the
latter part.
Let’s see how to write the same example using
extension methods.
IEnumerable<string> olderCustomersExtension =
customers
.Where(cust => cust.Age > 20)
.Select(cust => cust.Name);
All these extension methods are available on any
class that implements the generic IQueryable or IEnumerable<T> interfaces.
So what’s up with the ordering of the method calls, why do
we need to call the “Where” extension method before calling “Select”.
The answer is simple.
Where filters data that are returned from a data
source.
While Select narrows down the information that shown
in the final projection by specifying which
properties to retrieve.
So when I say customers.Select(cust =>
cust.Name) it just gives me a list of strings so customers.Select(cust => cust.Name).Where(cust => cust.Age >
20) will not be possible because now the Where clause don’t get a
customer object to query on.
Because of that when we are writing LINQ expressions we
should use the extension methods in the
correct order, otherwise you may get unexpected query results or
compilation errors.
Although the LINQ extension methods and types that are
defined in System.Linq namespace are very powerful, the syntax can be
quite cumbersome, and it is easy to introduce subtle errors that are difficult
to spot and correct.
To avoid these drawbacks designers of C# have provided an alternative approach to the use of
LINQ, through a series of LINQ query operators
that are part of the C# language.
There is an
equivalent query operator for each LINQ extension method.
Because these query operators are built to compliment the
functionality of the equalant extension methods. They should also follow the
above mentioned practices and rules to avoid any kind of side effects on the
data that will be retrieved by the LINQ expression.
Hope this clears things up!!