Sunday, August 17, 2008

A brief Tutorial about LINQ

LINQ (Language Intregated Query)
LINQ is a series of language extensions that supports data querying in a type-safe way. The data to be queried can take the form of XML (LINQ to XML), databases (LINQ-enabled ADO.NET, which includes LINQ to SQL, LINQ to Dataset and LINQ to Entities), objects (LINQ to Objects)
Before going to detail in LINQ, Let me tell you some intregal parts of LINQ:
1) Type Inference
Local type inference is a language feature that allows you to define variables and use them without worrying about their true type. Local type inference is also interchangeably known as implicitly typed local variables. The burden is put on the respective language compiler to determine the type of a variable by inferring it from the expression assigned to the variable. The result is type safety while allowing you to write more relaxed code, which is required to support Language Integrated Query (LINQ).Type inferred variables are strongly typed. The type cannot be changed once it is assigned as could be done with a variant type so it does not involve any casting operations or the resulting performance implications. A strong type is assigned, but simply done so by the compiler based on the results of the expression assigned to the variable.
A very basic example.
C# 2.0, you can write:
int i; i = 1;
C# 3.0,
you can also write this as:
var i = 1;
One More Example
var overdrawnQuery =
from account in accounts
where account.Balance < 0
select account ;
When the results of this query are iterated over using foreach, each element returned would consist of a name and address of an account that has a balance less than 0.

No comments: