Chapter 21. LINQ

As you saw in Chapter 20, SQL is a powerful tool for retrieving and filtering information from a database. Once you become accustomed to the syntax, with its selects and froms and joins, it’s somewhat intuitive as well. However, SQL commands don’t integrate well with C#, as you saw. You need the bridge of DataAdapter and DataSet objects to connect the database query with your application. The Language Integrated Query (LINQ) is the solution to that problem. LINQ is a new feature of .NET that C# 3.0 takes advantage of, which makes it easier to work with data, as you’ll see in the second part of the chapter.

Another useful feature of LINQ is that you can address a number of different data sources using similar syntax. In this chapter we’ll show you how to use LINQ with SQL, but you don’t need to use LINQ with a traditional database—it can retrieve data from XML files and other data sources equally well.

Perhaps the most interesting feature of LINQ is that you can query more than just data stored in other files. You can use LINQ to query collections that are held in-memory, that is, collection classes within your own code. So, for example, if you have a collection of Book objects, you can use LINQ to query for all the books by a single author, or published after a certain date. You could certainly write C# code to accomplish that, but the query syntax is arguably more natural and certainly briefer. Because this use of LINQ is easy to understand and is potentially useful, ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.