Monday, September 15, 2008

What is LINQ?

One of the few things I had to use more frequently in last few days is LINQ. Although LINQ is not a new topic I had to use it more frequently so I thought to write something about LINQ including my experiences in it.

It's not been so long since Microsoft has included typed-dataset in Visual Studio 2005 as their latest information access method. It seems that the next big challenge in programming is to reduce the complexity and time of information access. If you want to develop a database application using .net simplest approach was to use ADO.Net. ADO.Net works as the middle ware of your application. It provides a complete object oriented wrapper around the database. To develop a database application using ADO.Net you have to have a good knowledge in SQL as well as programming concepts. Visual Studio 2008 comes with the general purpose query facilities to .net framework which is applicable to various information sources not just relational data which is called Language-Integrated Query (LINQ).

LINQ provides a set of general purpose standard query operators to traverse, filter, order, etc... to facilitate those operations. It helps any .Net based programming language. These standard query operators are applicable to any kind of information source which implements the IEnumerable interface.

LINQ query/operators

string[] names = { "Ajantha", "Gayan", "Jennifer", "Leo",
"Nalaka", "Rasika", "Rajitha", "Randy" };

IEnumerable<string> query = from q in names
where q.Length == 6
orderby q
select q.ToUpper();

foreach (string name in query)

Response.Write(name + " ");

if you compile and run this code you'll see the output,

There are 3 standard query operators used in this query expression. where, orderby, select. This query expression can be re-written as,

IEnumerable<string> query = names
.Where(s => s.Length == 6)
.OrderBy(s => s)
.Select(s => s.ToUpper());

This type of a query is called a method based query. Arguments passed to Where, OrderBy, Select operators are called lambda expressions which are piece of codes or much like delegates. It allows to write individual query operators and bind together with the dot(.).

No comments:

Post a Comment