LINQ : .NET Language Integrated Query

LINQ : .NET Language Integrated Query

Rate This
  • Comments 3

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 http://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

 

Leave a Comment
  • Please add 5 and 6 and type the answer here:
  • Post
Page 1 of 1 (3 items)