LINQ : .NET Language Integrated Query

Applies To: .Net Framework 3.0

Another amazing gift from .NET is the .NET Language Integrated Query, popularly known as LINQ. The home page for LINQ has lots of resources https://msdn.microsoft.com/data/ref/linq/. If you download the Microsoft Visual Studio Code Name “Orcas” - LINQ CTP (May 2006) you will get the documents from Microsoft and the Hands on Lab. But to mention you here is that Suppose add-in still does not have the hundred percent IDE support with Visual Studio 2005. So the editor will give you the syntax warning but still your code will run after you compile it.

I have tried couple of the hands on in my PC and would like to share with you. Suppose you have an array containing series of integers and you would like to retrieve the even numbers from there. It is a matter of single line only. Here we go,

using System;

using System.Collections.Generic;

using System.Text;

using System.Query;

using System.Xml.XLinq;

using System.Data.DLinq;

namespace LINQConsoleApplication_CSharp

{

    class Program

    {

        static void Main(string[] args)

        {

            NumQuery();

            Console.ReadKey();

        }

        static void NumQuery()

        {

            var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            //Query with Lambda expression

            var evenNumbers =

                from p in numbers

                where (p % 2) == 0

                select p;

            Console.WriteLine("Result");

            foreach(var val in evenNumbers)

            {

                Console.WriteLine(val);

   }

        }

    }

}

 

Output would be something like (in console)

Result

2

4

6

8