LINQ is an acronym for Language-Integrated Query and a new feature in v3.5 of the .Net Framework from Microsoft. This new version of Microsoft .Net reached RTM status a couple of weeks ago — this framework is chock full of brilliant things I can use to improve my efficiency and effectiveness on daily tasks here at Pop Art.
As one of my favorite features, LINQ helps me write data-driven application even faster than what .Net 2.0 brought to the table. A common example starts with launching Visual Studio 2008. After dragging a collection of tables from a SQL Server database onto a surface in my solution, I can see a visualization of the columns in the tables as well as the relationships between them. Click the following thumbnail to see a larger image.
Next, I start writing data access code directly in my C# program as opposed to switching languages and writing in the T-SQL language. Visual Studio gives me Intellisense here too; as I type the name of a table and click the period key, all of the columns in the table appear where the cursor is located. Big time saver. Huge! I'm certain that I didn't misspell a column name and that my code will compile.
The syntax for LINQ in a C# program is very similar to the T-SQL language, which is a "set based" language. LINQ statements are compiled, just like the rest of my C# code. The first thing someone well versed in T-SQL will notice is that the columns normally specified in a SELECT query are at the end of the LINQ statement instead of the start as in T-SQL. The idea is that you're articulating your constraints at the start of the LINQ statement and then pulling out the fields you need at the very end.
Behind the scenes, LINQ is using the relationships expressed in the database to generate T-SQL scripts on the fly. This is a clear line of demarcation for LINQ. If you're using stored procedures exclusively for database access, then LINQ isn't going to buy you much. You'll still get Intellisense inside Visual Studio and you can specify an existing stored procedure instead of using the auto-generated SQL, but you're giving up a lot of acceleration tools. Perhaps more than you're getting in return.
LINQ really shines in multiple table joins and aggregation. The following two blocks of code show a query is performed in LINQ and its equivalent T-SQL script. The query retrieves product information from three tables where the list price is below a given amount and a sub-category name exists. If you go the T-SQL route, you will still need to write some C# code to call your database query.
Which of the following versions would you rather author and support?
LINQ Version
T-SQL Version
MSDN is a great online resource for developers and they really hit a home-run here. They have a page with 101 LINQ samples. This is my preferred way to learn when I already know the surrounding technologies and I want to fill in a specific gap. The page categorizes several ways of retrieving and iterating over information.