Get basic intuition about how LINQ works

By , 8 Nov 2011
Votes of 3 or less require a comment
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:

//goodGrades contains the numbers 82 and 97

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( //Where method is part of LINQ
this IEnumerable source, //LINQ is extending IEnumerable
Predicate predicate) //Predicate is special case of Func, it returns bool
{
IEnumerable res = new List();

foreach (T item in source)
{
if (predicate(item)) // Here if item is above 80 it will add to the result,
// g will be assigned each time to the current item(grade)
{
}
}

return res;
}
//...
}

Ok, so now after you gain enough intuition what happens,
Let's see the more realistic implementation of Where method:
1. It first checks for errors, then calls the implementaion method
2. 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); //If input is ok, let's go for the real stuff
}

private static IEnumerable WhereImpel(
IEnumerable source,
Predicate predicate)
{
foreach (T item in source)
{
if (predicate(item)) // Here if item is above 80 we return it..
{
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.

Software Developer GE
Israel
I am Software Developer at GE company for more than 2 years,

I created LINQTutorial.net since I didn't found any other good dedicate LINQ tutorial