Monday, September 16, 2013

LINQ : Query Execution -- Deferred vs Immediate

A LINQ query can be written to fetch the results immediately or at a latter point in time. To keep it simple, LINQ queries are often executed when the query is iterated over (via a foreach loop) -- as opposed to when the query variable is created. This is considered a “deferred” execution; however, queries can also be immediately executed when needed. For example, immediate execution is useful when the query results need to be cached or re-used.

From a syntax perspective, a query will execute immediately when the query returns a singleton (Min, Max, Count, Average, etc) or when it ends with .ToList, .ToArray, .ToDictionary, etc.

Deferred Example:

public static void DelayedExecString()
{
       //Create some data
string[] bikes = new string[] { "Yamaha""Honda""Ducati""Suzuki" };

//Build LINQ query
var simpleQuery =
    from bike in bikes
    select bike
    ;

//Query is NOW executed in a deferred manner
foreach (var type in simpleQuery)
{
    Console.WriteLine("Bike type is {0}", type);
}

Console.ReadLine();

}

Immediate Example:

public static void ImmediateExecString()
{
       //Create some data
string[] bikes = new string[] { "Yamaha""Honda""Ducati""Suzuki" };

//Build LINQ query
var simpleQuery = (
    from bike in bikes
    select bike).ToList();  //Query is NOW executed immediately

foreach (var type in simpleQuery)
{
    Console.WriteLine("Bike type is {0}", type);
}

Console.ReadLine();

}


No comments:

Post a Comment