Thursday, May 10, 2007

* LINQ : An Introduction

New to C# 3.0. LINQ (Language Integrated Query) extends the query capabilities of c# and Visual Basic in terms of querying and updating data using language syntax on any kind of data store. With Orcas the data stores mainly supported are in-memory objects, XML , SQL Server db objects, ADO.NET datasets. In future LINQ will also support querying on Entities exposed as part of ADO.NET Entity framework.

It supports compile time checking for syntax errors and type safety.

LINQ provides complete query language for any collection that implements IEnumerable<T> or IQueryable<T>. For in-memory objects to be enabled for LINQ, the object type should implement IEnumerable<T>. For LINQ to XML, SQL and Datasets the underlying provider converts the target objects to IEnumerable based collections.

Let’s see LINQ in action. Currently the most recommended way of trying LINQ id Beta 1 of Orcas which has LINQ framework integrated with it.

Consider the program below :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace HelloWorld


class Program


static void Main(string[] args)


string[] words = new string[5] { "Word1", "World", "Word2", "Word3", "Word4" };

IEnumerable<string> wordQuery =

from word in words

where word == "World"

select word;

foreach (string name in wordQuery)


Console.WriteLine("Hello " + name);





Output :

Hello World

In above program we query the list of words for a particular word ‘World’ and then prints ‘Hello World’ the number of times the word is found. Instead of using ‘if’ keyword, LINQ adds the capability of querying the local variables using very familiar SQL type querying capabilities.

With LINQ comes lot of new concepts which I will cover in detail very soon, but here is the list :

1. Immediate & Deferred execution of queries.

2. Forced Immediate Execution

3. Standard Query Operator Extension Methods

Other Posts


  1. Is it linq going to be a main thing for microsoft .net? Are they going to have it in too?

  2. VB.NET has also been enhanced to support LINQ.

  3. LINQ is a really good feature as it simplifies the work of the developers - a query tells the system what is required, rather than how to get the information (non-procedural).

    Since it uses the provider model, it also gives us the benefit of abstraction so we can plug-in a different provider when the source of the data is changed (such as when switching between the LINQ-to-SQL provider to something proprietary to get a bit of extra performance?).