Announced at PDC: The LINQ Project

The LINQ Project

On Tuesday September 13, 2005, Anders Hejlsberg did the first public demo of the LINQ Project in the Jim Allchin keynote.

What is LINQ you might ask?

LINQ stands for Language INtegrated Query and in a nutshell, it makes query and set operations, like SQL statements first class citizens in .NET languages like C# and VB.

Query expressions, like “from”, “where”, and “select” and all the others you know and love from SQL are now first class citizens in C# and VB. Not only that, the query expressions can be used across domains. While in this example I’m querying objects, I could just as easily query a database as well.

What does LINQ code look like?

The sample below queries a list of strings and returns all strings with a length of five.

using System;

using System.Query;

using Danielfe;

class Program

{

    static void Main(string[] args)

    {

        string[] aBunchOfWords = {"One","Two", "Hello",

  "World", "Four", "Five"};

    

        var result =

            from s in aBunchOfWords // query the string array

            where s.Length == 5 // for all words with length = 5

            select s; // and return the string

       

        //PrintToConsole is an Extension method that prints the value

        result.Print();

    }

}

This application prints the following result

Hello

World

The beauty of LINQ is that you can use query operations on anything. Here’s a sample that runs against SQL Server 2000 on the Northwind database and returns all customers who’s title is five.

using System;

using System.Query;

using Danielfe;

using System.Data.DLinq; //DLinq is LINQ for Databases

using nwind; //Custom namespace that is tool generated

class Program

{

    static void Main(string[] args)

    {

        Northwind db = new Northwind("Data Source=(local);Initial Catalog=Northwind;Integrated Security=True");

        Table<Customers> allCustomers = db.GetTable<Customers>();

        var result =

                from c in allCustomers

                where c.ContactTitle.Length == 5

                select c.ContactName;

        result.Print();

    }

}

The Customers class is an auto-generated class that lets you program against the customer table. The first two lines establish a connection to the database and retrieve data for the Customer table. The second line queries all northwind customers who’s ContactTitle is five characters long and returns the ContactName and prints them to the console.

In short, LINQ makes it a heck of a lot easier to program any sort of data source in a unified way.

More information: