The Three Stages of a LINQ Query

The Three Stages of a LINQ Query

Every LINQ query requires three stages:

  1. Obtain the data source(s)
  2. Create the query
  3. Execute the query

For example:

static void NumberGreaterThan5()

{

//The data source will be an array of integers

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

//Create the query

var ng5 = from n in numbers

where n > 5

orderby n

select n;

//Execute the query

foreach (int i in ng5)

{

Console.WriteLine(i);

}

}

Breaking down the code example:

The data source

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

The LINQ query

static void NumberGreaterThan5()

var ng5 = from n in numbers

where n > 5

orderby n

select n;

  1. The var keyword is used to define a strong-typed variable without having to identify that type – the compiler will figure it out based on the right-hand side of the equal sign.
  2. ng5 is our strong-typed object that will contain the results of our LINQ query
  3. n is our iterator variable which iterates through the numbers array. Notice how we do not specify the type of n either! The compiler will determine the type of n when the query is executed.
  4. The where statement defines our condition – Our condition in this example is to get all values from the numbers array which are greater than the number 5.
  5. The orderby statement will sort the results in ascending order
  6. The select statement specifies what values will be added to the ng5 object. Note that we could do interesting things to the select statement such as this:

    static void NumberGreaterThan5()

    var ng5 = from n in numbers

    where n > 5

    orderby n

    select n * 2;

Execute the LINQ query

It is not until we run the foreach statement that the LINQ query gets executed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s