Tuesday, April 22, 2008

When is a LINQ Statement Executed?

LINQ statements are the latest and greatest from Microsoft's .NET Framework. If used correctly they can make complex operations readable, maintainable and simple. Here is a simple example:


string[] characters = { "Ender", "Peter", "Valitine", "Stilson", "Graff", "Anderson" };

var eCharacters = from i in characters where i.Contains("e") select i;

foreach (string character in eCharacters)
// Do something with character

This sample shows a LINQ statement that extracts strings that contain an "e" from the character array. The characters would include Ender, Peter, Valitine and Anderson. One of the keys to understanding LINQ is understanding when this filtering actually occurs. Let's change the example a bit. In this example we will change the source (characters) so that Valitine will now be Val.

string[] characters = { "Ender", "Peter", "Valitine", "Stilson", "Graff", "Anderson" };

var eCharacters = from i in characters where i.Contains("e") select i;

characters[2] = "Val";

foreach (string character in eCharacters)
// Do something with character

The string array was changed after the LINQ statement. So will Valitine be included in eCharacters? No. LINQ statements do not execute until their values are enumerated over. This is called differed execution. If we wanted the LINQ statement to pull the values out at the time of execution we would need to enumerate through the values. Luckly with the extensions provided with LINQ we can do this very easily by changing our LINQ statement to something like this:

string[] eCharacters = (from i in characters where i.Contains("e") select i).ToArray<string>();

With a call to ToArray<string>() we enumerate over the LINQ result and create a string array. If the characters array changes, the values in the eCharacters array will not.

Save to del.icio.us Add to Technorati Add to dzone

No comments: