LINQ queries are deferred :)

by volkanuzun 3/28/2008 2:52:00 AM

Ok, probably we all heard that linq queries are deferred, so be careful bla bla.

Why is it deferred ? i think for performance, and resource use. By what makes linq queries less resource dependent ?
Let's have a quick look at the Where extension method.

public static IEnumerable<source>Where<source>(this IEnumerable<source> sourcelist, Func<source>, Boolen>predicate)
{
    foreach(source element in sourcelist)
    {
         if(predicate(element) yield return element;
    }
}

 

We can see that Where is an extension method (the first parameter is marked with "this" and it is a static function) of any IEnumerable object. 
What basically it does is to iterate through each element in the collection (IEnumerable collection), calling the function predicate for each element,
and if the element returns true in the predicate function; return the element. But it is smart enough not to return all the elements in once,
in stead it uses yield. yield retuns the current element and waits for the next call to return the next element, this makes it more effecient.
Also where method returns an IEnumerable object which means the result can be appended to Select, Where etc etc.

 

Tags:

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



About the author

Volkan Uzun




E-mail me Send mail

Twitter

Calendar

<<  December 2008  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Flickr Badge

www.flickr.com
This is a Flickr badge showing public photos from volkanuzun. Make your own badge here.

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Sign in