Introduction to LINQ

What is LINQ?

Language Integrated Query (LINQ) is a Microsoft .Net Framework component which adds native date querying capabilities to .Net languages. LINQ unifies the way data can be retrieved in .Net, from any object which implements the IEnumerable interface.

In the diagram above, the top level shows the languages that provide full native support for LINQ (currently C# 3.0 and VB 9.0), while the middle level represents the three main parts of the LINQ project.

Linq to Objects

LINQ to object is an API that provides methods to a set of standard query operators that retrieve data from any object whose class implements the IEnumerable interface.  These queries are performed against in-memory data.

Linq to Ado.Net

The LINQ to Ado.Net argument works with relational data. It is composed of three parts:

  • Linq to XML:
    used to query relational databases such as Microsoft SQL Server
  • Linq to Dataset:
    supports queries by using data sets and data tables
  • Linq to Entities:
    allows developers to use entities to declaratively specify the structure of business objects, and use LINQ to query them

Linq to XML

Linq to XML provides an in-memory xml programming interface that leverages the .Net language-Integrated Query.

LINQ to Objects

LINQ to Objects allows .Net developers to write “Queries” over a collection of objects. There is a large set of query operators that provide a same depth of functionality to what we expect from other SQL languages, while working with a relational database. When not present, we can add our own.

Traditionally, working with a collection of objects will take more time. We would write a lot of looping code, using the for loop to iterate through the list, carrying out filtering using if statements. LINQ makes it easy to get the result without using loops. It will allow you to write queries and filter a list, or calculate the aggregate functions on the elements in a collection as a set.

You can write queries against the collection type which implements an interface called IEnumerable. This is almost any collection type built into the .Net Class libraries, including simple arrays like string[] or int[], that we define.

Let’s see some simple examples of the basic syntax.

Consider a list of numbers. From those numbers we have to display only 5 numbers in ascending order.

4, 1, 5, 9, 3, 5, 3, 0

The traditional way is to store them in arrays, and using loops we will rearrange them into ascending order, then display the top five numbers in the ascending order.

But using LINQ is very simple. See the following example

  1. Dim nums As Integer() = New Integer() {4, 1, 5, 9, 3, 5, 3, 0}
  2. Dim result = From n In nums _
  3. Where n < 5 _
  4. Order By n _
  5. Select n
  6. For Each i As Integer In result
  7. Console.WriteLine(i)
  8. Next
Dim nums As Integer() = New Integer() {4, 1, 5, 9, 3, 5, 3, 0}
        Dim result = From n In nums _
            Where n < 5 _
            Order By n _
            Select n
        For Each i As Integer In result

In the first line we have created an integer type array, and stored all of the numbers. We then created result as an object type using the LINQ query



Aggregate Operators

Next we will see some examples for the aggregate operators of Count, Sum, Min and Max


We are going to find the odd numbers in the list


  1. Dim numbers As Integer() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
  2. Dim oddNumbers As Integer = numbers.Count(Function(n) n Mod 2 = 1)
  3. Console.WriteLine(“There are {0} odd numbers in the list.”, oddNumbers)
Dim numbers As Integer() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
Dim oddNumbers As Integer = numbers.Count(Function(n) n Mod 2 = 1)
Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers)


There are 5 odd numbers in the list

We first stored the set of integer values in the numbers array. The oddNumbers variable will hold the total odd number value. The Object.count() function will help you to find the total number of odd values. Inside the count() function we have another recursive function which finds the count of the result of the mod. If it returns 1 then 1 will be added. In the above list there are 5 odd numbers available (5, 1, 3, 9, and 7).


Sum() is used to find the sum of the array.


  1. Dim numbers As Integer() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
  2. Dim numSum As Double = numbers.Sum()
  3. Console.WriteLine(“The sum of the numbers is {0}.”, numSum)
Dim numbers As Integer() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
Dim numSum As Double = numbers.Sum()
Console.WriteLine("The sum of the numbers is {0}.", numSum)


The sum of the numbers is 30

First we stored the 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 numbers in an array number. Using the object.sum() function we stored the sum of the values in the numSum variable.

You can use the min,max and Average() functions in the same way

numbers.Min() – Get the minimum number from an array
numbers.Max() – Get the maximum number from an array
numbers.Average() – Get the average value from the set of array elements.

Set Operators

The set operator in LINQ includes Except, Distinct, Intersect, and Union

  1. Dim twos As Integer() = {1, 2, 3, 4, 5}
  2. Dim threes As Integer() = {2, 4, 6, 7, 10}
  3. Dim intersection = twos.Intersect(threes)
  4. For Each n In intersection
  5. Console.WriteLine(n)
  6. Next
Dim twos As Integer() = {1, 2, 3, 4, 5}
Dim threes As Integer() = {2, 4, 6, 7, 10}
Dim intersection = twos.Intersect(threes)
For Each n In intersection



The example above shows the distinct of two integer arrays. The numbers 2 and 4 exist in both arrays

Using another example we can display the concatenation of two arrays first and second

  1. Dim first As Integer() = {1, 2, 3, 4, 5}
  2. Dim second As Integer() = {2, 4, 6, 7, 10}
  3. Dim intersection = first.Union(second)
  4. For Each n In intersection
  5. Console.WriteLine(n)
  6. Next
  7. Console.ReadLine()
Dim first As Integer() = {1, 2, 3, 4, 5}
        Dim second As Integer() = {2, 4, 6, 7, 10}
        Dim intersection = first.Union(second)
        For Each n In intersection

The Union() function will help to join the two arrays.

Generation Operators


The following example uses Repeat to generate a sequence that contains the number 5, ten times.

  1. Dim numbers = Enumerable.Repeat(5, 10)
  2. For Each n In numbers
  3. Console.WriteLine(n)
  4. Next
Dim numbers = Enumerable.Repeat(5, 10)
         For Each n In numbers

Ordering Operators

Following example sorts the list of words alphabetically.


  1. Dim MyWords As String() = {“cherry”, “apple”, “blueberry”}
  2. Dim sortedWords = From w In MyWords _
  3. Order By w _
  4. Select w
  5. Console.WriteLine(“The sorted list of words:”)
  6. For Each w In sortedWords
  7. Console.WriteLine(w)
  8. Next
Dim MyWords As String() = {"cherry", "apple", "blueberry"}
        Dim sortedWords = From w In MyWords _
            Order By w _
            Select w
        Console.WriteLine("The sorted list of words:")
        For Each w In sortedWords


The sorted list of words:

In the above example first we created a string array, and stored the values “cherry”, “apple”, and “blueberry” in the MyWords array. The sortedWords object will stored the values, which are returned by the LINQ query. The values will be sorted in ascending order, then the for each loop will display the sorted words.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s