Wednesday 24 May 2017

LINQ 01 Basics

Language Integrated Query in short known as LINQ is a c# syntax for querying collections. The collection can be anything, it could be a list of ints or an array of objects; it can be a representation of xml or database data as long as it implement either the IEnumerable or IQueryable interface.

LINQ comes in two flavors
  • "Expression" based which looks like upside down SQL 
  • "Method" based which is made up of extension methods found in the IEnumerable or IQueryable interfaces
lets take a look at a trivial example

class Program
{
    static void Main(string[] args)
    {
        //Create Number array
        int[] Numbers = Enumerable.Range(0, 20).ToArray();

        //use foreach to get even numbers
        List<inteven1 = new List<int>();
        foreach (int n in Numbers)
            if (n % 2 == 0)
                even1.Add(n);

        //use expression linq to get even numbers
        IEnumerable<int> even2 = from i in Numbers
                                 where i % 2 == 0
                                 select i;

        //use method based linq to get even numbers
        IEnumerable<int> even3 = Numbers.Where(i => i % 2 == 0);
    }
}

now lets lets use the "var" keyword to take advantage of implicit types allowing the compiler to determine what our type is.

using System;
using System.Collections.Generic;
using System.Linq;

namespace pc.linq00
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Number array
            int[] Numbers = Enumerable.Range(0, 20).ToArray();

            //use foreach to get even numbers
            var even1 = new List<int>();
            foreach (int n in Numbers)
                if (n % 2 == 0)
                    even1.Add(n);

            //use expression linq to get even numbers
            var even2 = from i in Numbers
                        where i % 2 == 0
                        select i;

            //use method based linq to get even numbers
            var even3 = Numbers.Where(i => i % 2 == 0);

            foreach (var n in even1)
                Console.Write(n + " ");
            Console.WriteLine("\n");
            foreach (var n in even2)
                Console.Write(n + " ");
            Console.WriteLine("\n");
            foreach (var n in even3)
                Console.Write(n + " ");
            Console.WriteLine("\n");
        }
    }
}

When you run the application and step through it you'll notice that when the foreach statement executes the execution keeps transferring between the foreach statement and the where clause in the LINQ query. This is because the LINQ query isn’t actually executed until the container (in this case our even2 and even3 collections) is used. This is called deferred execution.