Datasheet
Klein c01.tex V3 - 12/13/2007 1:48pm Page 6
Part I: Introduction to Project LINQ
on the same level as objects and classes). So, you can now enjoy the benefits of a single declarative pattern
that can be expressed in any .NET-based programming language.
The result of making these set operations, transforms, and constructs first-class operations is a set of
methods called the standard query operators. These operators provide query capabilities that include
sorting, filtering, aggregation, and projection over a large number of different data sources. The standard
query operators are the focus of Chapter 4, ‘‘LINQ Standard Query Operators.’’
Think about it for a minute. A single set of query operators that work within any .NET-based
programming language, enabling you to write a query against a database, XML, or an in-memory array
using the same syntax? How cool is that? And you get the added benefit of IntelliSense and compile-time
type checking! Somebody pinch me.
To illustrate this great technology, take a look at an example that queries the directories of your C drive
and writes them to a list box:
DirectoryInfo di = new DirectoryInfo("C:
\\
");
var dirQuery =
from dir in di.GetDirectories()
orderby di.Name
select new { dir.Name} ;
foreach {var item in dirQuery)
listBox1.Items.Add(item.Name);
This code uses some of the standard query operators to create a LINQ query. In essence, Microsoft has
taken the concept of query set operations and made them first-class operations within the
.NET Framework.
Here’s another example. This one queries all the system processes on your PC using the
Process
class,
but notice that it uses the same query syntax as the previous example:
var procQuery =
from proc in Process.GetProcesses()
orderby p.WorkingSet64 descending
select new { p.Id, p.ProcessName, p.WorkingSet64} ;
foreach (var item in procQuery)
ListBox1.Items.Add(item.Id + " " +
item.ProcessName + " " +
item.WorkingSet64);
When you run this code, all the processes on your system will be listed in descending order by
memory usage.
Simply put, LINQ enables you to query anything that implements the
IEnumerable
<
T
> interface. If you
can loop through the contents using the
foreach
statement, then you can query it using LINQ.
The following example illustrates how LINQ works querying relational data, using a database as the
source of data.
6