Sunil Jagadish

LINQ – Language INtegrated Query

leave a comment »

Language INtegrated Query (LINQ) is an extension to the capabilities of .NET languages (currently C# 3.0 and VB 9.0) to perform SQL-like operations on any source of data. The conventional data sources that we’ve been using today are databases, flat files, XML documents etc. LINQ defines certain standard query operators that enable set operations, traversal, projection, selection, join (the relational algebra stuff) to be performed on non-conventional sources of data, which is IEnumerable<T>-based. This means that you can use LINQ to query data from sources such as the enumeration of the list of processes running on your machine. I found this neat example here.

To get started with LINQ, you need to download the LINQ SDK (May 2006). I delivered a session on LINQ at the BDotNETStudent UG meet.

One of my demos included querying a String collection.

Code:

string[] names = {"Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David"};
var q = names
           .Where(s => s.Length > 4)
           .OrderBy(s => s.Length)
           .Select(s => s);
foreach(var i in q)
           Console.WriteLine(i);

A simple query which selects those names from the collection which have a length greater than 4 and the same is then ordered based on the length of each string (in ascending order).

The output:

Frank
David
Burke
George
Harris
Connor
Albert
Everett

Here you’d observe that though “Burke” appears before “Frank” in the original collection, after the execution of the query, the order isn’t preserved. This is because; the OrderBy operator implements an unstable sort algorithm to order the elements.The subtle difference between OrderBy in LINQ and SQL is that, in case of SQL, a query like-

select * from tab_names order by len(sname)

would result in:

Burke
Frank
David
Albert
George
Harris
Connor
Everett

Links:

LINQ Project on MSDN
Download LINQ SDK
LINQ Samples
Anders Hejlsberg on LINQ [Channel9 video]
LINQ Intro

Advertisements

Written by Sunil

2006.06.04 at 11:50 AM

Posted in .NET, Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: