Home

Introduction to the Language Integrated Query

   

The Language Integrated Query

 

Introduction to Querying

When using a list of values or a collection of records, a query is a list created or selected from another existing list. This is usually the basis for a computer database. In fact, a whole computer language was developped on that theory. This means that until now, to create a query, you mostly had to work in a formal database environment. To make it possible to create a query based on any type of list, Microsoft created the Language Integrated Query, abbreviated LINQ.

The LINQ is a data manipulated language (DML) used to create a list or sub-list derived from an existing list or a collection of records. The LINQ is part of the .NET Framework. It is used along with normal C# code.

Starting to LINQ

To support the ability to query a list, the .NET Framework provides the Language Integrated Query or LINQ. To use the LINQ in your application, you must include the System.Core.dll assembly in your program. If you started your application as an empty project:

  • On the main menu, click Project -> Add Reference...
  • In the Solution Explorer, right-click the name of the project -> Add -> Reference...
  • In the Solution Explorer, right-click References and click Add Reference...

In the .NET tab of the Add Reference dialog box, you can click System.Core

Add Reference

Then click OK. You must then include the System.Linq namespace in your code or you can include the using System.Linq; line in your list of namespaces.

If you create an application by selecting the Windows Forms Application option from the New Project dialog box, the studio would add the necessary assemblies to your project and the necessary namespaces to your code file.

Creating a Query

To query a list, you write a statement using words and operators of the LINQ. The most fundamental operation you can perform on LINQ consists of creating, also referred to as selecting, or querying, a list of values or records, from an existing list. The basic formula to use is:

var SubListName = from ValueHolder in List select ValueHolder;

The var keyword, the assignment operator "=", the from keyword, the in keyword, the select keyword, and the semicolon are required.

The SubListName is a name of a new variable that will hold the list of values produced by this operation.

The ValueHolder is the name of a variable that will be used to identify each resulting member of this operation. This variable will be equivalent to getting each member of the list.

The List factor represents the name of the variable that you would have created already. The List can be an array. When the statement ends, the SubListName is the list that is produced. That's the list you will used outside the statement.

Querying an Array

As you may be aware already, the array is the most fundamental type of list in C#, and you should know already how to create an array of values. Here is an example of an array of integers:

var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

The array is also the most fundamental list you can query. From our formula, the simplest query you can perform on an array consists of getting its values and storing them in a query variable. To do this, from our formula, replace SubListName with a variable name of your choice. Replace ValueHolder with the name that will be selected at the end. Replace List with the name of your array. Here is an example of simply querying an array:

using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Exercise : Form
{
    private ListBox lbxNumbers;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lbxNumbers = new ListBox();
        lbxNumbers.Location = new System.Drawing.Point(12, 12);
        lbxNumbers.Width = 100;

        Text = "Numbers";
        MinimizeBox = false;
        MaximizeBox = false;
        Controls.Add(this.lbxNumbers);
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(130, 145);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        var number = from n in numbers select n;

        foreach (var member in number)
            lbxNumbers.Items.Add(member.ToString());
    }

    [STAThread]
    public static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Numbers

To make the code easier to read, you can spread the statement to various lines. Here is an example:

var number = from n
	     in numbers
	     select n;

In the same way, you can query an array of decimal numbers or strings, etc. Here is an example:

using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Exercise : Form
{
    private ListBox lbxMovies;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lbxMovies = new ListBox();
        lbxMovies.Location = new System.Drawing.Point(12, 12);
        lbxMovies.Size = new System.Drawing.Size(160, 80);

        Text = "Movie Collection";
        MinimizeBox = false;
        MaximizeBox = false;
        Controls.Add(this.lbxMovies);
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(190, 120);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var movies = new string[] { "Two for the Money", 
                                    "Her Alibi", 
                                    "Distinguished Gentleman (The)",
                                    "Memoirs of a Geisha", 
                                    "Wall Street" };

        var movie = from n in movies select n;

        foreach (var title in movie)
            lbxMovies.Items.Add(title.ToString());
    }

    [STAThread]
    public static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Movie Collection

 
 
 

Using a Criterion to Select a List

 

Where is the Condition

Simply using a select statement as done above produces the same list of values in the array. A criterion is a condition applied to a set of values to find out which one(s) respond(s) to a condition to validate one or some values. When applied to a list, a criterion examines each member, finds out what member responds to the condition and, if so, adds that member to the from list.

To apply a criterion, you create a Boolean operation between the in statement and the select statement. This criterion is actually formulated using an operator named where. The formula to use is:

var SubListName = from ValueHolder in List where Condition select ValueHolder;

In the new section, the where keyword is required. The Condition is formulated using one of the logical operators you are already familiar with from the C# language. It can be in the form of:

  • ValueHolder == SomeValue: If ValueHolder is the same as SomeValue, the list member that is being examined is valid. This operator can be applied to integers and strings. You should avoid using this operator on decimal values because it is difficult and can be unpredictable when comparing two decimal numbers (such as 12.55 and 12.5503 or 12.55 and 12.5582) for equality
  • ValueHolder < SomeValue: If ValueHolder is less than SomeValue, the list member that is being examined is valid. This operator can be applied to numbers of all kinds. You should never use it on strings
  • ValueHolder <= SomeValue: If ValueHolder is the same as, or lower than, SomeValue, the list member that is being examined is valid. This operator can be applied to integers. You should never use it on strings. Although you can, you shoukd avoid using this operator on decimal numbers for the same reason we gave for ==
  • ValueHolder > SomeValue: If ValueHolder is greater than SomeValue, the list member that is being examined is valid. This operator can be applied to numbers of all kinds. You should never use it on strings
  • ValueHolder >= SomeValue: If ValueHolder is the same as, or greater than, SomeValue, the list member that is being examined is valid. This operator can be applied to integers and not to strings. You shoukd avoid using this operator on decimal values
  • ValueHolder != SomeValue: If ValueHolder is different from SomeValue, the list member that is being examined is valid. This operator can be applied to all types of numbers and to strings
  • !(ValueHolder == SomeValue): If ValueHolder is different from SomeValue, the list member that is being examined is valid. This operator can be applied to all types of values

Remember that you must create the criterion as a Boolean operation. After applying the select statement, you can use it as you see fit. Here is an example:

using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Exercise : Form
{
    private ListBox lbxNumbers;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lbxNumbers = new ListBox();
        lbxNumbers.Location = new System.Drawing.Point(12, 12);
        lbxNumbers.Width = 100;

        Text = "Numbers";
        MinimizeBox = false;
        MaximizeBox = false;
        Controls.Add(this.lbxNumbers);
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(130, 145);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var numbers = new double[] { 12, 445, 25, 380, 6, 285, 2448, 32, 6320, 4 };

        var number = from n
                     in numbers
                     where n == 445
                     select n;

        foreach (var member in number)
            lbxNumbers.Items.Add(member.ToString());
    }

    [STAThread]
    public static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Numbers

The purpose of querying a list is to isolate one or more values. As such, you can create an expression that checks a value and applies some condition to it. For example, in this list of numbers, you may want to find out whether it contains one or more numbers that are divisible by 5. This operation can be carried by the % operator as in "number % 5"; but number % 5 is pure algebra, not Boolean. Therefore, you must add a condition to make it a valid Boolean expression. For example, you can find out if the "number % 5" operation is equal to 0. Here is an example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 12, 445, 25, 380, 6, 285, 2448, 32, 6320, 4 };

    var number = from n
                 in numbers
                 where n % 5 == 0
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

This would produce:

Numbers

To make the statement easier to read and less confusing, you should isolate the groups of statements in parentheses:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 12, 445, 25, 380, 6, 285, 2448, 32, 6320, 4 };

    var number = from n
                 in numbers
                 where (n % 5) == 0
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

Negating a Condition

You can create a criterion that works perfectly but rather want its opposite. To get it, you can negate the expression. To do this, you use the ! operator of the C# language. To make the expression easy to read, you should include it in parentheses. That is, put the ! operator in the beginning of the logical expression followed by parentheses that include the actual logical expression. Here is an example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 12, 445, 25, 380, 6, 285, 2448, 32, 6320, 4 };

    var number = from n
                 in numbers
                 where !((n % 5) == 0)
                 select n;

    foreach (var member in number)
        lbxNumbers.Items.Add(member.ToString());
}

This would produce:

Numbers

In the same way, you can negate a where condition that involves any appropriate value.

 
 
   
 

Home Copyright © 2014, FunctionX Next