Published on 07-08-2015

LINQ for Beginners

This tutorial will introduce you to the basics of the LINQ framework, and give you a rundown of the LINQ architecture, data providers and query structure.

Introduction

Before LINQ was introduced as part of the .NET framework in Visual Studio 2008, developers had to query data collections with good-old loops and conditional statements. The code produced, was not easy on the eye, and it was prone to errors. Have a look at this code snippet, which demonstrates how data may be accessed without LINQ:

int[] numbers = { 3, 6, 7, 9, 2, 5, 3, 7 };
int i = 0;

// Display numbers larger than 5
while (i < numbers.GetLength(0))
{
    if (numbers[i] > 5)
        Console.WriteLine(numbers[i]);

    ++i;
}

Fortunately LINQ came to the rescue, and made code like the above a thing of the past. With LINQ, data sources could now be queried in an SQL-like syntax, as shown in the rewritten code snippet below:

int[] numbers = { 3, 6, 7, 9, 2, 5, 3, 7 };

var res = from n in numbers
          where n > 5
          select n;

foreach (int n in res)
    Console.WriteLine(n);

You will recognize many SQL statements called the same in LINQ, like Select, Where, Distinct and Group By.

Data Providers

You may be interested in querying data from various sources, such as arrays, dictionaries, xml and entities created from entity framework. But instead of having to use a different API for each data source, LINQ provides a consistent and uniform programming model to work with all supported data sources. Put in other words, the LINQ query for fetching an element from an array and an xml file will look very much alike.

Some of the most used LINQ data sources, which are all part the .NET framework, are:

As long as you include the namespace System.Linq in your code, you are good to go with all of the above data sources.

Architecture

You can use LINQ from all the popular .NET languages (C#, VB.NET and F#) as illustrated in the architecture overview below. The languages may query any LINQ Data Source, with the help of the layer called .NET Language Integrated Query (LINQ).

LINQ Architecture.
Figure 1: LINQ Architecture.

It is worth noting, that even though all .NET languages share the same LINQ layer (the green rounded rectangle), some of the languages are more LINQ "enabled" than others. F# for example, provides more LINQ functionality than C# and VB.NET.

Query structure

LINQ offers two ways to write queries: 1) with SQL-like syntax called Query expressions or 2) a method like approach called Lambda expressions

Let’s take a small example to give a better view of the query structure: In a collection of random numbers we want to retrieve only values greater than 50, sort them in ascending order, and lastly cast the result into strings. This would normally require quite a lot of code lines, if you were to do this with loops and code conditions, but with a LINQ query expression you can simply write:

int[] numbers = { 7, 53, 45, 99 };

var res = from n in numbers
          where n > 50
          orderby n
          select n.ToString();

A query expression always starts with "from element in collection", and iterates over each element in the collection. Like in SQL statements, you can filter or project your query further, as we did with where, orderby and select. The last statement, "select n.ToString()" projects the end result into strings (“53” and “99”).

You could also have written this as a Lambda expression, as mentioned earlier. You then get a method-like structure:

int[] numbers = { 7, 53, 45, 99 };

var res = numbers.Where(n => n > 50)
                 .OrderBy(n => n)
                 .Select(n => n.ToString());

The "n => n …" creates an instance of each iterated element in the collection. What is on the left side of "=>" is the input parameters, and on the other side is the expression.

You can read more about the difference between Lambda and Query expressions in this "Should I use Lambda or Query Syntax?" tutorial.

I hope this tutorial was helpful in introducing you to LINQ. If you have any questions, feel free to write it in a comment below.