Introduction to LINQ

By Admin at 30 Mar 2010, 16:37 PM
  • 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 AsInteger() = New Integer() {4, 1, 5, 9, 3, 5, 3, 0}
    2. Dim result = From n In nums _
    3. Where n < 5 _
    4. OrderBy n _
    5. Select n
    6. For Each i AsIntegerIn result
    7. Console.WriteLine(i)
    8. Next

    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 AsInteger() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
    2. Dim oddNumbers AsInteger = numbers.Count(Function(n) n Mod 2 = 1)
    3. 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 AsInteger() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
    2. Dim numSum AsDouble = numbers.Sum()
    3. 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 AsInteger() = {1, 2, 3, 4, 5}
    2. Dim threes AsInteger() = {2, 4, 6, 7, 10}
    3. Dim intersection = twos.Intersect(threes)
    4. For Each n In intersection
    5. Console.WriteLine(n)
    6. Next



    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 firstAsInteger() = {1, 2, 3, 4, 5}
    2. Dim secondAsInteger() = {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()

    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

    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. OrderBy w _
    4. Select w
    5. Console.WriteLine("The sorted list of words:")
    6. For Each w In sortedWords
    7. Console.WriteLine(w)
    8. Next


    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.



    Post a comment

    Please correct the following: