Datasheet
Klein c01.tex V3 - 12/13/2007 1:48pm Page 10
Part I: Introduction to Project LINQ
table to return the
DirectoryDescription
information from the table. Just add the following highlighted
code to the earlier query:
DirectoryInfo di = new DirectoryInfo("C:
\\
");
var query =
from dir in di.GetDirectories()
orderby di.Name
select new
{
dir.Name,
DirectoryDescription = (
from d in db.DirectoryInformation
where d.DirectoryName == di.Name
select d.DirectoryDescription).FirstOrDefault()
};
foreach (var item in query)
listBox1.Items.Add(item.Name + " " + item.DirectoryDescription);
}
To run this example, you first need to create a table in a database. The example used the AdventureWorks
database and the following code to create the table:
CREATE TABLE [dbo].[DirectoryInformation](
[DirectoryName] [varchar](50) NULL,
[DirectoryDescription] [varchar](255) NULL
) ON PRIMARY
GO
You can use the following
INSERT
statement to add data to the
DirectoryInformation
table:
INSERT INTO DirectoryInformation (DirectoryName, DirectoryDescription)
VALUES (’Windows’, ’My Windows Directory’)
GO
Before continuing, think about the amount of code you would have had to write to accomplish the same
type of query in pre-LINQ technology. In the space of about two dozen lines, you were able to access
data, query that data, and loop through that data simply and efficiently. In other technologies, you would
have had to create a connection to the database, create an instance of a
SqlCommand
object and any other
objects needed to execute a query, and write T-SQL code in your .NET code enclosed in quotation marks
And that’s not to mention all the work that has to be done once you get the data back—casting to the
appropriate data types, and so on.
The good news is that LINQ does all of that for you. Sweet! And we haven’t even covered XML yet.
Standard Query Operators
The LINQ standard query operators make up an API that provides the means of querying various
data sources, such as arrays, collections, and even XML and relational data. They are a set of methods
that are implemented by each specific LINQ provider (LINQ to SQL, LINQ to XML, LINQ to Objects,
10