Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Get basic intuition about how LINQ works

5.00/5 (1 vote)
8 Nov 2011CPOL 13.6K  
Deep Look in the basics of LINQ
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:

C#
List<int> grades = new List<int>{76,97,82};
List<int> goodGrades = grades.where(g => g > 80).ToList();
                       //goodGrades contains the numbers 82 and 97


Let's try to understand what happened here?
C#
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.

C#
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)
        {
          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:
  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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)