Search This Blog

Saturday, May 1, 2010

Getting Started With LINQ

Introduction to LINQ:
LINQ stands for Language Integrated Query. This is new technology in latest .Net Framework 3.5.
“Microsoft original motivation behind LINQ was to address the impedance mismatch between programming languages and database.”
-Anders Hejlsberg
What is LINQ?
If someone wants to develop database application on .Net platform the very simple approach he uses ADO.Net. ADO.Net is serving as middle ware in application and provides complete object oriented wrapper around the database SQL. Developing application in C# and VB.Net, so developer must have good knowledge of object oriented concept as well as SQL, so it means developer must be familiar with both technologies to develop an application.
LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.
LINQ defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes (implementing IEnumerable interface), XML, relational database, and third party data sources. While it allows any data source to be queried, it requires that the data be encapsulated as objects. So, if the data source does not natively store data as objects, the data must be mapped to the object domain. Queries written using the query operators are executed either by the LINQ query processing engine or, via an extension mechanism, handed over to LINQ providers which either implement a separate query processing engine or translate to a different format to be executed on a separate data store (such as on a database server as SQL queries). The results of a query are returned as a collection of in-memory objects that can be enumerated.

LINQ and Productivity:
Increase productivity and reduce run-time errors in your applications by using strongly typed objects instead of embedded SQL query syntax.
1) Optimize development efforts: Help to become more productive and optimize the overall application development effort by using a single consistent query language for all aspects of the application
2) Reduce bugs and errors (due to compile time checking): LINQ Works with strongly typed CLR objects that reduce run-time errors in applications. Identify query-related coding errors at compile time and reduce the debugging effort by using strongly typed variables
3) Be more productive with Microsoft Visual Studio: Maximize developer efficiency when writing code that includes strongly typed data objects and take full advantage of the productivity enhancing capabilities of Visual Studio, such as the object browser and IntelliSense, debugging, and rich refactoring support
4) Extensibility: LINQ let you to easily adapt to the needs of a particular application scenario by taking advantage of several data source-specific implementations of LINQ to query various types of data.
Which is the Assembly for LINQ?
The base LINQ functionality is located in Syste.Core.dll. All Default projects in VS 2008 readily include reference to this assembly. The Namespace for LINQ is “System. Linq”.
For inline coding in ASP.net add
<%@ import Namespace=”System. Linq” %>
For Code Behind Model
using System.Linq;

Types LINQ Query: There are three basic types of LINQ queries.
a) LINQ to Objects
b) LINQ to XML
c) LINQ to SQL

LINQ to Objects: It enables to perform complex query operations against any Enumerable object (i.e. the object which implements IEnumerable Interface).
Time to Get Your Hand Dirty: We first Write Simple Console Application say ”LINQ2OBJ”
Code is Listed Below: Code has been well iced with comments we call this listing (1.0).Just copy
In your Visual studio file Program.cs and see Basic LINQ in action.

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


namespace LINQ2OBJ
{
class Program
{
static void Main(string[] args)
{
/**using**var**keyword***from*****C#3.0*****
* var saves the hassels of casting,
* finding object type quick and
* dirty(PHP guys we Have it Now!)
********************************************/

/*Reads the Collection of Person Objects*/
var objDataStore = GetMyFriends();

/*The Simple select using LINQ*/
var linqQuery = from p in objDataStore select p;

/*Why Not use getEnumerator from 2.0*/
Console.WriteLine("**********Using Enumerator***********");
var em = linqQuery.GetEnumerator();

/*Classic C/C++ programmer are fond of while loop while new kids hate*/
while (em.MoveNext())
{
Console.WriteLine("FirstName:" + em.Current.Fname);
}
Console.WriteLine("**********Normal Style***********");

/*Normal Style of iteration using beloved foreach*/
int i = 0;
foreach (Person p in linqQuery)
{
Console.WriteLine("**********"+i+"th person*****************");
Console.WriteLine("FirstName:"+p.Fname);
Console.WriteLine("MiddleName:" + p.Mname);
Console.WriteLine("LastName:" + p.Lname);
Console.WriteLine("Age:" + p.Age);
Console.WriteLine("BirthDate:" + p.Birthdate);
Console.WriteLine("Single:" + p.Single);
Console.WriteLine("***************************");
i++;
}
Console.ReadKey();
}

public static List GetMyFriends()
{
List _returnvalue = new List();
Person[] PersonArray = new Person[5];
int _i = 0;
while(_i < 5){
/*Lamba Style Initialization*/
PersonArray[_i] = new Person { Fname = "F" + _i, Mname = "M" + _i, Lname = "L" + _i, Age = 28, Single = true, Birthdate = DateTime.Now.AddYears(28 - _i) };
_returnvalue.Add(PersonArray[_i]);
_i++;
}
return _returnvalue;
}
}
/*class that saved the day*/
class Person
{
/*C# 3.0 Style of declaring Property*/
public string Fname{ get; set; }
public string Mname{ get; set; }
public string Lname{ get; set; }
public int Age{ get; set; }
public bool Single{ get; set; }
public DateTime Birthdate{ get; set; }
}
}