Query Expressions

Query expressions are special statements used for querying a knowledge supply exploitation the LINQ. LINQ square measure simply extension ways that you simply decision and returns the info that you simply need. These ways square measure placed in the System.Linq namespace thus {you must|you need to|you need to} embody it once you want to use LINQ in your project. question expressions square measure translated into their equivalent technique syntax that may be understood by CLR. you’ll find out about exploitation the tacticsyntax for querying information exploitation LINQ within the next lesson.

Let’s take a look at the first example of using LINQ query expression to query values from a collection. Note that we are using LINQ to Objects so we will simply use a simple array as the source.

using System;
using System.Linq;
 
namespace LinqExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 1, 2, 3, 4, 5 };
 
            var result = from n in numbers 
                         select n;         
 
            foreach (var n in result)
            {
                Console.Write(n + " ");
            }
        }
    }
}

Example 1

1 2 3 4 5

Line 2 imports the System.Linq namespace so that we can use LINQ in our program. Line 10 declares an array of 5 integers containing some values. Line 12-13 is the simplest query expression you can make although it is currently useless right now, but we will be studying more forms of query expressions. This query expression simply gets every number from the  numbers array which can then be accessed using the results variable. The structure of a basic query  expression is as follows:

var query = from rangeVar in dataSource
            <other operations>
            select <projection>;

Example 2 – Structure of a basic query expression

Note that you can write a query expression in a single line, but a good  practice is to separate each clause into multiple lines. Each line of the  formatted query expression above is called a clause. There are seven types of  clauses you can use in a query expression which includes, fromselectwhereorderbyletjoin, and group-by  clauses. For now, we will be only looking at the from and selectclauses.

Query expressions begin with the a from clause. The from clause uses a range variable (rangeVar) which will temporarily hold a value from the data Source,  followed by the in a contextual keyword and then the data source itself. This can be compared to the mechanisms of the foreach loop wherever a spread variable can hold every price retrieved from the supply. however the vary variable in a fromclause is totally different because it solely acts as a regard to every consecutive part of the information supply. this is often due to the postponed execution mechanism that you’ll learn later. The vary variable mechanically observe its kind mistreatment kind reasoning supported the sort of each part from the information supply.

After a from clause, you can insert one or more whereorderbylet, or join clauses.  You can even add one or more from clauses which  will be demonstrated in a later lesson.

At the tip of a question expression is a select clause. Following the select keyword could be a projection which can confirm the form or variety of every came part. For example, if a worth following the select clause is of type int, then the kind of the question are a assortment of integers. you’ll even perform additional styles of projection and transformation techniques which can be incontestible in a very later lesson. Note that a question expression may also be all over with a group-by clause, however a separate lesson are dedicated for it.

So to wrap up, a typical query expression starts with a from clause with a range variable and a data  source, then followed by any of the fromwhereorderbylet, or join  clauses, and finally the select or group-by clause at the end of the query  expression.

If you know SQL, then the syntax of the query expression might look weird to you because the from clause is placed first and the select clause is placed last. This was done so that Visual Studio can use the Intellisense feature by knowing what type an item of the data source is in advance.

The keywords used in a query expression such as from and select are examples of contextual keywords. They are only treated as keywords during specific events and locations such as a query expression. For example, you can simply use the word select as a variable name if it will not be used in a query expression. To see the complete list of contextual keywords

The result of the query is of type IEnumerable<T>. If you will look at our example, the result was placed in a variable of type var which means it uses type inference to automatically detect the type of the queried data. You can, for example, explicitly indicate the type of the query result like this:

IEnumerable<int> result = from n in numbers
                          select n;

but it requires you to know the type of the result in advance. It is recommended to use var instead to take advantage of a lot of its features.

Line 15-18 of Example 1 shows the value of every data from the query. We simply used a foreach loop, but you must also take note that we used var as the type of the range variable. This allows the compiler to simply detect the type of every data in the query result.

The LINQ has a feature called deferred execution. It means the question expression or LINQ methodology won’t execute till the program starts to browse or access AN item from the results of the question. The question expression really simply returns a computation. the particular sequence of information are retrieved once the user asks for it. to Illustrate, the question expression are dead after you access the results victimization a foreach loop. you may learn a lot of concerning postponed execution a bit bit later.

We have successfully written our very first query expression, but as you can see, it does nothing but to query every data from the data source. Later lessons will show you more techniques such as filtering, ordering, joining, and grouping results.  We will look at each of the seven query expression clauses in more depth.