Wednesday, October 22, 2008

LINQ ,iterators and Lazy loading

When I first started exploring LINQ queries ,I was excited about lot of its features, particularly the lazy loading of results.

Linq query that retrieves only customer info
var names= for c in db.customer
where c.name.contains("Sree")
select c.name;

Linq query that retrieves customer and some order info
var result = from c in db.customer
where c.orders.orderdate<'01/01/2009'
select c.name, c.orders.orderdate;

So basically if you have a customer entity and orders for that customer, when you access customer, the orders will not be retreived,. it gets filled when you access one of the property of order class. there are ways to change this behavoiur to do full loading.

After knowing that I did some research on what is happenng behind the scenes. so it turned out that LINQ is using the iterator feature and yield keyword to achieve this behaviour.

So when you write a foreach loop as you all know it uses an iterator. Within the iterator you can use the yield keyword to return results one by one or as desired

private static IEnumerable GetOrders()
{
yield return "Order1";
yield retun "Order2";
}

In the above example I have return multiple yield statements, but it could be a loop with one yield statement inside.

nice to know how some things work..

No comments: