Query over objects using LINQ just like you do tables with SQL

“The LINQ Project is a codename for 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.”

That’s right! You can query over objects using LINQ just like you do tables using SQL. For example, let’s assume you have a table called “numbers” that has a single column of type int called “number” like this:

If you wanted to get all the rows with a value greater than 5 you would write the following SQL:

SELECT number FROM numbers WHERE (number > 5)

Your result would be:

6

7

8

9

10

Now consider an array of numbers (all code sinppets are in C#):

int[] numbers = new int[] {1,2,3,4,5,6,7,8,9,10};

Using LINQ you can write a SQL-like syntax to query over the array:

var results = from number in numbers

where number > 5

select number;

foreach (int i in results)

{

Console.WriteLine(i);

}

The output on the console would be:

6

7

8

9

10

You are probably wondering to yourself “If I can query over objects, then I need an Object Relational Mapping (ORM) capability to go along with this new powerful query capability that’s now part of my programming language.” You’re right! However, the really powerful thing here is that we’ve separated the query functionality from the ORM technology. The core query capability of LINQ (Standard Query Operators) works with plain old CLR objects. Then there is XLinq (for Xml) and DLinq (for databases). DLinq is the ORM piece of LINQ. This means that you can query over XML, data in a database, and plain old CLR objects all at once. Ponder that for a moment… Yep, you can JOIN or UNION (among many other things) XML, relational data, and in memory objects into a single result. There is so much more to LINQ (VB/C#, Visual Studio designer support, query over DataSet, etc.), but I think I’m reaching the “This blog is too long” point.

Soma has a nice post about LINQ here. The MSDN landing page for LINQ is here. You can download the Microsoft Visual Studio Code Name “Orcas” - LINQ CTP (May 2006) here. The download includes a plethora of documentation and hands on labs.

-Marc

Technorati Tags: Microsoft, .NET, Object Relational Mapping, ORM