Table of Contents
Introduction
About This Book
Conventions Used in This Book
What You Should Read
What You Don’t Have to Read
Foolish Assumptions
How This Book Is Organized
Part I: An Overview of LINQ
Part II: Using Standard LINQ to Technologies
Part III: Extending LINQ to New Horizons
Part IV: The Part of Tens
The accompanying Web site
Icons Used in This Book
Where to Go from Here
Part I: An Overview of LINQ
Chapter 1: Getting to Know LINQ
Considering LINQ
Understanding the task that LINQ performs
Contemplating why you need LINQ
Defining the LINQ design goals
Understanding the LINQ requirements
Using LINQ in the Real World
Understanding Declarative Programming
An Overview of the LINQ Namespaces
System.Linq namespace
System.Linq.Expressions namespace
System.Data.Linq namespace
System.Data.Linq.Mapping namespace
System.Data.SqlClient namespace
System.Data.SqlClient.Implementation namespace
System.Xml.Linq namespace
Chapter 2: Creating Simple LINQ Queries
Defining the LINQ Keywords
Working with from
Working with where
Working with orderby
Working with join
Working with let
Creating a Simple from Query
Understanding the simple query application code
Using the debugger to see the simple query in action
Filtering a Query
Grouping Queries
Creating Queries from Multiple Sources
Understanding the multiple-source application code
Working with the alternative multiple-source example
Using calculated values in multiple-source queries
Working with the Standard Query Operators
Chapter 3: Considering the .NET Language Ex tensions
An Overview of the Language Extensions
Working with Lambda Expressions
Understanding the Role of the IEnumerable and IEnumerable<T> Interfaces
Understanding Object Initializers
Understanding Collection Initializers
Working with Extension Methods
Working with Partial Methods
An Overview of Expression Trees
Working with Query Expressions
Chapter 4: Working with LINQ in Visual Basic .NET
Understanding the Visual Basic Differences
Creating the Simple Visual Basic Example
Working with From
Working with Where
Working with Order By
Working with Join
Working with Let
Using the Additional Visual Basic Keywords
Working with Aggregate
Working with Distinct
Working with Skip
Working with Take
Working with Lambda Functions in Visual Basic
Chapter 5: Working with LINQ in Visual Studio 2005
Obtaining LINQ Support for Visual Studio 2005
Installing LINQ Support
Creating the Simple Visual Studio 2005 Project
Defining the project
Working with from
Working with join
Working with where
Working with orderby
Working with let
Part II: Using Standard LINQ to Technologies
Chapter 6: LINQ to Object
Considering the Use of Objects with LINQ
Creating the Simple Object Query Example
Understanding the Role of Deferred Operators
Creating the Deferred Operator Examples
Working with Concat
Working with AsEnumerable, AsQueryable, Cast, and OfType
Working with OfType and Where
Working with DefaultIfEmpty, Empty, Range, and Repeat
Working with GroupBy and ToLookup
Working with GroupJoin and Join
Working with Skip, SkipWhile, Take, and TakeWhile
Working with Select and SelectMany
Working with Distinct, Except, Intersect, and Union
Working with OrderBy, OrderByDescending, Reverse, ThenBy, and ThenByDescending
Understanding the Role of Nondeferred Operators
Creating the Nondeferred Operator Examples
Working with Aggregate, Average, Count, LongCount, Max, Min, and Sum
Working with ToArray, ToDictionary, ToList, and ToLookup
Working with ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last, LastOrDefault, Single, and SingleOrDefault
Working with SequenceEqual
Working with All, Any, and Contains
Chapter 7: LINQ to DataSet
Considering the Use of DataSets with LINQ
Creating the Simple DataSet Example
Defining the test tables
Outputting the results
Exploring the connection
Understanding the LINQ to DataSet Operators
Creating the Filtered Output Example
Creating a simple display
Modifying the filtered output
Using the CopyToDataTable operator
Working with typed DataSets
Working with Multiple DataSet Tables
Chapter 8: LINQ to SQL Server
Considering the Use of SQL Server with LINQ
Obtaining and Installing the Northwind Database
Downloading the database
Installing the database
Testing the Visual Studio connection
Generating the Northwind entity classes and XML mapping files
Creating the Simple SQL Server Query Example
Overcoming the Visual Studio 2008 connectivity issues
Defining the project
Adding the code
Viewing the debugger output
Using Object Relational Designer
Understanding the LINQ to SQL Server Operators
Chapter 9: LINQ to XML
Considering the Use of XML with LINQ
Working with the LINQ to XML API
Understanding the LINQ to XML Operators
Working with XDeclaration, XElement, and XDocument
Working with XNamespace
Working with XProcessingInstruction
Working with XAttribute
Working with XComment and XText
Working with XCData
Working with XDocumentType
Working with XNodeDocumentOrderComparer
Working with XNodeEqualityComparer
Working with Remove
Working with XName
Creating the Simple XML File Example
Creating the project
Building an XML document
Saving an XML document
Loading an XML document
Part III: Extending LINQ to New Horizons
Chapter 10: Using LINQ with Office 2007
Understanding the Office Document Structure
Understanding LINQ Interaction with Office
Obtaining the Required Library
Creating the Office 2007 Document Example
Creating the project
Understanding the custom properties
Reading document properties
Writing document properties
Chapter 11: Advanced LINQ to SQL Server
Considering SQL Server Issues
Understanding concurrency problems
Overcoming performance issues
Creating the Database Modification Example
Performing an insert
Performing an update
Performing a delete
Using Concurrency Checks and Resolving Errors
Resolving conflicts at the object level
Resolving conflicts at the member level
Chapter 12: LINQ to Active Directory
Working with Specific Active Directory Objects
Defining Active Directory Variables
Obtaining the LINQ to Active Directory Provider
Creating the Simple Active Directory Query Example
Performing the project setup
Defining an Active Directory object class
Creating a root node pointer
Reading user information
Writing user information
Understanding the Limitations of Active Directory Interaction
Some LINQ methods aren’t implemented
Defining the need for LDAP patience
Chapter 13: Other LINQ to Strategies
Understanding the Qualifications for a LINQ to Solution
Accessing COM+ Using LINQ
COM+ accessed as a Web service
COM+ accessed using interop functionality
Creating the Resource Description Format (RDF) Files Example
A quick overview of RDF
A quick overview of SPARQL
Starting the project
Configuring the project
Creating the host application
Creating the application class definition
Reading RDF files
Creating the MySQL Example
Getting the MySQL ADO.NET connector
Compiling the DbLinq.DLL and DbLinq.MySQL.DLL files
Configuring the database
Defining the MySQL project
Developing the query code
Part IV: The Part of Tens
Chapter 14: Ten Ways to Improve LINQ Development
Using LINQ Tools to Simplify Coding
Getting the VLinq add-in application
Creating a VLinq query
Using a VLinq query in an application
Using LINQ to Create Self Documenting Code
Analyzing Code Patterns
Querying a Code Snippet Database
Locating Other Development Resources
Using LINQ to Query Data Formats
Finding Usage Trends
Developing a LINQ Library
Sharing LINQ Queries with Others
Analyzing Compiler and IDE Output
Chapter 15: Ten Ways to Reduce Application Support Costs
Creating Self-Modifying Queries
Using LINQ to Create Reports
Addressing User Search Needs
Creating User-Friendly Mashups
Making Help More Accessible
Organizing and Querying Support Requests and Responses
Developing Fast Searches from Multiple Sources
Helping Users Locate Existing Resources
Performing Support Task Automation
Improving Application and System Management
Chapter 16: Ten LINQ Resources
Starting with the Microsoft Developer Network
Getting Tips from the Microsoft Blogs
Finding Help in Third-Party Web Sites
Finding Help in Third-Party Newsletters and Blogs
Using Other Sources for LINQ to Objects Projects
Using Other Sources for LINQ to SQL Server Projects
Using Other Sources for LINQ to XML Projects
Considering Other LINQ to Sources Projects
Getting Help with Visual Basic Projects
Getting Help with C# Projects
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Website is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make. Further, readers should be aware that Internet Websites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
When John isn’t working at the computer, you can find him in his workshop crafting wood projects or making candles. On any given afternoon, you can find him working at a lathe or putting the finishing touches on a bookcase. He also likes making glycerin soap, which comes in handy for gift baskets. You can reach John on the Internet at Mueller@mwt.net. John is also setting up a Web site and blog at http://www.johnmuellerbooks.com; feel free to look and make suggestions on how he can improve it.
This book is dedicated to my friend Osvaldo Téllez Almirall (Chicho). We’ve had many conversations about music and life in general and I’ve always felt that I came away a better person for them.
Thanks to my wife, Rebecca, for working with me to get this book completed. I really don’t know what I would have done without her help in researching and compiling some of the information that appears in this book. She also did a fine job of proofreading my rough draft.
Russ Mullen deserves thanks for his technical edit of this book. He added greatly to the accuracy and depth of the material that you see here. I appreciated the time he devoted to checking my code for accuracy. As I wrote this book, I also spent a good deal of time bouncing ideas off Russ, which is a valuable aid to any author.
Matt Wagner, my agent, deserves credit for helping me get the contract in the first place and taking care of all the details that most authors don’t consider. I always appreciate his assistance. It’s good to know that someone wants to help.
A number of people read all or part of this book to help me refine the approach, test the examples, and generally provide input that every reader wishes they could have. These unpaid volunteers helped in ways too numerous to mention here. I especially appreciate the efforts of Osvaldo Téllez Almirall, who provided me with some interesting bits of information. Bill Salkin gave me some good ideas. Andrew Matthews provided me with significant help and coding examples for the LINQ to RDF provider. In fact, a number of people made suggestions on how to improve my coding technique. I’d like to thank each person who wrote me with an idea by name, but there are simply too many.
Finally, I would like to thank Katie Feltman, Susan Pink, and the rest of the editorial and production staff for their assistance in bringing this book to print. It’s always nice to work with such a great group of professionals.
We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/.
Introduction
Language INtegrated Query (LINQ) sounds like some kind of formless question that depends on how someone speaks. Of course, your queries are integrated with your language! How can you make them otherwise?
LINQ is actually a new feature of .NET Framework that expands your grasp well beyond things Microsoft. In fact, after playing with LINQ for quite some time I thought I’d start to run out of new data sources to query, but it hasn’t happened yet. You can use LINQ to query just about anything (and I only say “just about” because I’m sure there is something LINQ can’t reach).
The thing that should excite you most about LINQ is that it helps you access technologies that you couldn’t ordinarily access or couldn’t do so with ease. For example, you can use LINQ to access MySQL easily, without considering a workaround. You can also access Resource Description Framework (RDF) files, something that would be tough without LINQ. You get all of these additional opportunities to access varied data sources and you’ll write less code, not more, to do it. LINQ is truly one of the most interesting features that Microsoft has ever added to .NET Framework, and you’d miss out on a lot if you didn’t explore the LINQ technology for your own programming needs.
About This Book
LINQ For Dummies is your gateway to a new world — one in which you can ask questions (programmatically) of literally anything. This book starts with the basics. You need to discover the LINQ basics before you can begin pulling information from Active Directory, but LINQ is so small compared to many technologies that the basics require only a few pages. Most of this book is about getting serious work accomplished.
After working with LINQ for a while, I discovered that there are inequities in the LINQ world. For one thing, it seems as if Microsoft is avoiding Visual Basic .NET because their Web site has a decided lack of Visual Basic .NET materials. It was hard to find Visual Basic .NET examples on third-party Web sites too. I hope that this situation will change, but for now you have Chapter 4, which tells you the Visual Basic .NET side of the story, and Chapter 16, which provides you with a host of Visual Basic .NET resources.
The second inequity that LINQ For Dummies addresses is the needs of the Visual Studio 2005 developer. It appears that everyone assumes you have Visual Studio 2008. Although most of this book was written with Visual Studio 2008 in mind, there isn’t any reason you can’t write LINQ applications using Visual Studio 2005, and Chapter 5 provides the information you need. The remaining examples in the book will even work with Visual Studio 2005 with a little tweaking.
You’ll also find a host of example types in LINQ For Dummies. For example, did you know that you can access the content of Office 2007 documents using LINQ? Chapter 10 tells you about all of the interesting things you can do with Office 2007 once you have LINQ at your disposal. The astonishing thing is that you can perform these tasks with little code. Using LINQ, it’s possible to both read and write Office 2007 documents without resorting to odd programming strategies.
LINQ can also make your life as a developer considerably easier. Chapter 14 provides an array of interesting techniques you can use to obtain information about your applications that you might not have even thought available. Only in LINQ For Dummies can you find all of these mind-boggling techniques in one place.
Conventions Used in This Book
I always try to show you the fastest way to accomplish any task. In many cases, this means using a menu command such as File⇒New⇒Project. When working with LINQ, I’ll tell you which dialog box tab to access first, and then which feature to use on that tab.
This book also uses special type to emphasize some information. For example, entries that you need to type appear in bold. All code, Web site URLs, and on-screen messages appear in monofont type. When I define a new word, you’ll see that word in italics.
Because you use multiple applications when you’re working with LINQ, I always point out when to move from one application to the next. When a chapter begins, I introduce the main application for that chapter. All the commands in that chapter are for the main application until I specifically tell you to move to another application. I also tell you when it’s time to move back to the main application.
What You Should Read
Anyone who doesn’t have any LINQ experience should read all of Part I. It’s possible to skip Chapter 1 if you don’t want to know about the array of LINQ providers already on the market or the other interesting things you can do with LINQ, but most people have a number of special needs and Chapter 1 is where you discover how to fulfill them.
Someone who’s been exposed to LINQ but hasn’t worked with it can probably skip Part I and begin with Part II. Make sure you read the chapters in turn. No, the chapters don’t provide interlocked information, forcing you to grind through one chapter at a time, but the LINQ to DataSet provider does build on the LINQ to Objects provider, so you need to know both to create a LINQ to Objects application.
If you’re familiar with the basic LINQ to providers (you have written programs using them) and just want to see the other things that LINQ can do, you’ll want to start with Part III. In some cases, you may have questions about a particular technique and you can refer to Parts I and II when you need to answer such questions. Part III doesn’t provide quite as much hand holding, so you do need to know how LINQ works to use it.
What You Don’t Have to Read
Most of the chapters contain some advanced material that will interest only some readers. When you see one of these specialized topics (such as the requirements for using COM+ in Vista and Windows Server 2008 in Chapter 13), feel free to skip it. Most of this advanced material appears in sidebars and some of it applies only when you use a specific operating system. The sidebar title will always indicate the special nature of the advanced material.
You can also skip any material marked with a Technical Stuff icon. This material is helpful, but you don’t have to know it to work with LINQ. I include this material because I find it helpful in my programming efforts and hope that you will, too.
Foolish Assumptions
You might find it difficult to believe that I’ve assumed anything about you — after all, I haven’t even met you yet! Although most assumptions are indeed foolish, I made these assumptions to provide a starting point for the book.
I’m assuming that you’ve worked with Windows long enough to know how the keyboard and mouse work. You should also know how to use menus and other basic Windows features. It’s also essential to know how to use the Visual Studio IDE and that you know at least one .NET language. This book doesn’t provide any instruction on how to write applications outside the instructions needed to write LINQ applications. If you don’t know what a foreach loop is, you definitely require a different book.
Some portions of the book work with Web pages and others use XML; you need to know at least a little about these technologies to use those sections. You don’t have to be an expert in any of these areas, but more knowledge is better. You must also have a very good knowledge of the programming language you use to work with LINQ.
This is a book for someone who has development experience. I’m assuming that you have a very good knowledge of either Visual Basic .NET or C#. You must also know how to work with any extension technology you want to access. For example, if you want to write a LINQ query to access COM+, you need to know something about COM+ before you can read about it in this book. The same holds true for Active Directory, RDF, MySQL, Office 2007, or any of the other extension technologies described in the book.
How This Book Is Organized
This book contains several parts. Each part demonstrates a particular LINQ concept. In each chapter, I discuss a particular topic and include example programs that you can use to discover more about LINQ on your own. You can find the source code for this book on the Dummies.com Web site at http://www.dummies.com/go/linqfd.
Part I: An Overview of LINQ
Part I looks at LINQ as a technology and introduces you to essential concepts such as the operators used to create a LINQ query. In addition, this part reviews the .NET Framework technologies that make LINQ queries possible. This is also the part of the book that helps you use LINQ with both Visual Basic .NET and Visual Studio 2005. One of the central themes of this part of LINQ For Dummies is helping you discover all the tasks that LINQ can perform.
Part II: Using Standard LINQ to Technologies
.NET Framework comes with four providers. A provider is a link between your application and the data source it requires. Each of the four LINQ providers that come with .NET Framework appear in a separate chapter in Part II. Using just these four providers, you can query any object, any data set, any kind of XML, and SQL Server. These four providers cover a lot of ground. Just knowing them will give you access to a considerable range of data, much of which isn’t even hosted on Windows.
Part III: Extending LINQ to New Horizons
The four basic LINQ providers can perform quite a few tasks, but they have limits. Sometimes it isn’t a matter of being able to access the data, but merely one of accessing the data without a lot of extra programming. Part III shows how you can combine third-party providers with LINQ to create some remarkable applications. Because the applications in this part of the book are unique, you’ll want to skip around a bit and read about the technologies that interest you the most first.
Part IV: The Part of Tens
The final part of the book provides you with some helpful tips and resources you can use to make your LINQ development experience even better. Chapter 14 shows how you can use LINQ to create a better development environment for yourself. Chapter 15 helps you discover ways to use LINQ to make the application environment better for users and support staff, while reducing your workload. Chapter 16 provides ten truly useful resources that will help reduce your development time. If you have the idea by now that LINQ is all about making things easier, you have understood the intent of this book.
The accompanying Web site
This book contains a lot of code, and you might not want to type it. In fact, it’s probably better if you don’t attempt to type this code manually. Fortunately, you can find the source code for this book on the Dummies.com Web site at http://www.dummies.com/go/linqfd. The source code is organized by chapter, and I’ll always tell you about the example files in the text. The best way to work with a chapter is to download all the source code for it at one time.
Icons Used in This Book
As you read this book, you’ll see icons in the margins that indicate material of interest (or not, as the case may be).This section briefly describes each icon in this book.
Tips are nice because they help you save time or perform some task without a lot of extra work. The tips in this book are timesaving techniques or pointers to resources that you should try to get the maximum benefit from LINQ.
I don’t want to sound like an angry parent or some kind of maniac, but you should avoid doing anything marked with a Warning icon. Otherwise, you could find that your program melts down and takes your data with it.
Whenever you see this icon, think advanced tip or technique. You might find these tidbits of useful information just too boring for words, or they could contain the solution you need to get a program running. Skip these bits of information whenever you like.
If you don’t get anything else out of a particular chapter or section, remember the material marked by this icon. This text usually contains an essential process or bit of information that you must know to write LINQ programs successfully.
Where to Go from Here
It’s time to start your LINQ adventure! I recommend that anyone who has only a passing knowledge of LINQ go right to Chapter 1. This chapter contains essential, get-started information that you need for writing your first LINQ program.
If you already have some LINQ experience, move right to Chapter 6. It is important to know about the four LINQ providers that come with .NET Framework. Otherwise, you might find that it’s hard to understand how the third-party LINQ providers described in Part III work. If you desperately need LINQ on your next project, read through Chapter 6 first before you move on to Part III because every LINQ provider available today builds on the LINQ to Objects provider.