Looking at
LINQ for the first time, it may look like magic.
Looking at the code behind can take you to another level of understanding.
So let's examine a very simple scenario:
List<int> grades = new List<int>{76,97,82};
List<int> goodGrades = grades.where(g => g > 80).ToList();
Let's try to understand what happened here?
g => g > 80
This Lambda defines a predicate which returns
true
if
g
is grater than
80
.
The
Where
method iterates over each item in grades list and if item is above
80
, it will get into
goodGrades
list.
public static class Enumerable
{
public static IEnumerable Where(
this IEnumerable source,
Predicate predicate)
{
IEnumerable res = new List();
foreach (T item in source)
{
if (predicate(item))
{
res.Add(item);
}
}
return res;
}
}
Ok, so now after you gain enough intuition what happens,
Let's see the more realistic implementation of
Where
method:
- It first checks for errors, then calls the implementaion method
- WhereImpel method use the yeild return keyword*
public static class Enumerable
{
public static IEnumerable Where(
this IEnumerable source,
Predicate predicate)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
return WhereImpel(source, predicate);
}
private static IEnumerable WhereImpel(
IEnumerable source,
Predicate predicate)
{
foreach (T item in source)
{
if (predicate(item))
{
yield return item;
}
}
}
/...
}
*If you are not familiar with
yield return
keyword, each time the result is being accessed, it returns one item.
In this example,
ToList()
method is chained to the
Where
query, so
goodGrades
list will be assigned only once.
yield return
is the mechanism that allows LINQ where operation to be
deferred execution.
I hope you now understand LINQ a little better.
This tip is part of a larger article of
Lambda Expression.