Linq Unleashed for C#

Paul Kimmel

Image
800 East 96th Street, Indianapolis, Indiana 46240 USA

Linq Unleashed for C#

Library of Congress Cataloging-in-Publication Data

Kimmel, Paul.
   LINQ unleashed for C# / Paul Kimmel. — 1st ed.
          p.cm.
   ISBN 978-0-672-32983-8
   1. C# (Computer program language) 2. Microsoft LINQ. I. Title.
     QA76.73.C154K5635 2009
     005.13’3—dc22
                                                                    2008030703
Printed in the United States of America
First Printing August 2008

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book.

Bulk Sales

Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact

U.S. Corporate and Government Sales
1-800-382-3419
[email protected]

For sales outside of the U.S., please contact

International Sales
[email protected]

Editor-in-Chief

Karen Gettman

Executive Editor

Neil Rowe

Development Editor

Mark Renfrow

Managing Editor

Kristy Hart

Project Editor

Betsy Harris

Copy Editor

Karen Annett

Indexers

Lisa Stumpf

Publishing Works

Proofreader

Linda Seifer

Technical Editor

Joe Kunk

Publishing Coordinator

Cindy Teeters

Cover Designer

Gary Adair

Compositor

Jake McFarland

Contents at a Glance

Introduction

Part I Getting Ready for LINQ

1 Programming with Anonymous Types

2 Using Compound Type Initialization

3 Defining Extension and Partial Methods

4 yield return: Using .NET’s State Machine Generator

5 Understanding Lambda Expressions and Closures

6 Using Standard Query Operators

Part II LINQ for Objects

7 Sorting and Grouping Queries

8 Using Aggregate Operations

9 Performing Set Operations

10 Mastering Select and SelectMany

11 Joining Query Results

12 Querying Outlook and Active Directory

Part III LINQ for Data

13 Querying Relational Data with LINQ

14 Creating Better Entities and Mapping Inheritance and Aggregation

15 Joining Database Tables with LINQ Queries

16 Updating Anonymous Relational Data

17 Introducing ADO.NET 3.0 and the Entity Framework

Part IV LINQ for XML

18 Extracting Data from XML

19 Comparing LINQ to XML with Other XML Technologies

20 Constructing XML from Non-XML Data

21 Emitting XML with the XmlWriter

22 Combining XML with Other Data Models

23 LINQ to XSD Supports Typed XML Programming

Index

Table of Contents

Introduction

Conventions Used in This Book

Part I Getting Ready for LINQ

1 Programming with Anonymous Types

Understanding Anonymous Types

Programming with Anonymous Types

Defining Simple Anonymous Types

Using Array Initializer Syntax

Creating Composite Anonymous Types

Using Anonymous Type Indexes in For Statements

Anonymous Types and Using Statements

Returning Anonymous Types from Functions

Databinding Anonymous Types

Testing Anonymous Type Equality

Using Anonymous Types with LINQ Queries

Introducing Generic Anonymous Methods

Using Anonymous Generic Methods

Implementing Nested Recursion

Summary

2 Using Compound Type Initialization

Initializing Objects with Named Types

Implementing Classes for Compound Initialization Through Named Types

Understanding Auto-Implemented Properties

Initializing Anonymous Types

Initializing Collections

Finishing the Hypergraph

Implementing the Hypergraph Controls Using the Observer Pattern

Using Conversion Operators

ToArray

OfType

Cast

AsEnumerable

ToList

ToDictionary

ToLookup

Summary

3 Defining Extension and Partial Methods

Extension Methods and Rules of the Road

Defining Extension Methods

Implementing Extension Methods

Overloading Extension Methods

Defining Generic Extension Methods

How Extension Methods Support LINQ

Implementing a “Talking” String Extension Method

Defining Partial Methods

Summary

4 yield return: Using .NET’s State Machine Generator

Understanding How yield return Works

Using yield return and yield break

Profiling Code

Using yield break

Summary

5 Understanding Lambda Expressions and Closures

Understanding the Evolution from Function Pointers to Lambda Expressions

Writing Basic Lambda Expressions

Automatic Properties

Reading Lambda Expressions

Lambda Expressions Captured as Generic Actions

Searching Strings

Lambda Expressions Captured as Generic Predicates

Binding Control Events to Lambda Expressions

Dynamic Programming with Lambda Expressions

Using Select<T> with Lambda Expressions

Using Where<T> with Lambda Expressions

Using OrderBy<T> with Lambda Expressions

Compiling Lambda Expressions as Code or Data

Lambda Expressions and Closures

Currying

Summary

6 Using Standard Query Operators

Understanding How LINQ Is Implemented

Constructing a LINQ Query

Filtering Information

Using Quantifiers

Partitioning with Skip and Take

Using Generation Operations

DefaultIfEmpty

Empty

Range

Repeat

Equality Testing

Obtaining Specific Elements from a Sequence

Appending Sequences with Concat

Summary

Part II LINQ for Objects

7 Sorting and Grouping Queries

Sorting Information

Sorting in Ascending and Descending Order

Sort in Descending Order Using the Extension Method Directly

Performing Secondary Sorts

Reversing the Order of Items

Grouping Information

Summary

8 Using Aggregate Operations

Aggregating

Averaging Collection Values

Counting Elements

Finding Minimum and Maximum Elements

Summing Query Results

Median: Defining a Custom Aggregation Operation

Summary

9 Performing Set Operations

Finding Distinct Elements

Finding Distinct Objects Using Object Fields

Defining Exclusive Sets with Intersect and Except

Creating Composite Resultsets with Union

Summary

10 Mastering Select and SelectMany

Exploring Select

Selecting with Function Call Effects

Manipulating Select Predicates

Returning Custom Business Objects from a Data Access Layer

Using Select Indexes to Shuffle (or Unsort) an Array

Forming the Basis of a Card Game Like Blackjack

Projecting New Types from Calculated Values

Importing DLLs

Using GDI+ with Windows API (or External DLL) Methods

Using Select to I-Cap Words

Projecting New Types from Multiple Sources

Creating a New Sequence from Multiple Sequences with SelectMany

Using SelectMany with Indexes

Summary

11 Joining Query Results

Using Multiple From Clauses

Defining Inner Joins

Using Custom, or Nonequijoins

Defining a Nonequal Custom Join

Defining a Custom Join with Multiple Predicates

Defining Custom Joins with a Temporary Range Variable

Implementing Group Join and Left Outer Join

Defining a Group Join

Implementing a Left Outer Join

Implementing a Cross Join

Defining Joins Based on Composite Keys

Summary

12 Querying Outlook and Active Directory

LINQ to Outlook

Querying Active Directory with Straight C# Code

LINQ to Active Directory

Creating an IQueryable LINQ Provider

Implementing the IQueryProvider

Defining Active Directory as the Data Source

Converting a LINQ Query to an Active Directory Query

Implementing Helper Attributes

Defining Active Directory Schema Entities

Querying Active Directory with LINQ

Summary

Part III LINQ for Data

13 Querying Relational Data with LINQ

Defining Table Objects

Mapping Classes to Tables

Viewing the Query Text Generated by LINQ

Connecting to Relational Data with DataContext Objects

Querying DataSets

Selecting Data from a DataTable

Querying the DataTable with a Where Clause

Using Partitioning Methods

Sorting Against DataTables

Defining a Join with DataSets

SqlMetal: Using the Entity Class Generator Tool

Using the LINQ to SQL Class Designer

Summary

14 Creating Better Entities and Mapping Inheritance and Aggregation

Defining Better Entities with Nullable Types

Mapping Inheritance Hierarchies for LINQ to SQL

Creating Inheritance Mappings with the LINQ to SQL Designer

Customizing Classes Created with the LINQ to SQL Designer

Adding EntitySet Classes as Properties

Creating Databases with LINQ to SQL

Summary

15 Joining Database Tables with LINQ Queries

Defining Joins with LINQ to DataSet

Coding Equijoins

Coding Nonequijoins

Defining a Left Join and a Word about Right Joins

Considering Right Joins

Defining Joins with LINQ to SQL

Coding Equijoins

Implementing the Group Join

Implementing a Left Join

Querying Views with LINQ

Building a View in SQL Server

Querying a View with LINQ to SQL

Databinding with LINQ to SQL

Summary

16 Updating Anonymous Relational Data

Adding and Removing Data

Inserting Data with LINQ to SQL

Deleting Data with LINQ to SQL

Updating Data with LINQ to SQL

Using Stored Procedures

Calling User-Defined Functions

Using Transactions

Understanding Conflict Resolution

Indicating the Conflict Handling Mode for SubmitChanges

Catching and Resolving Concurrency Conflicts

N-Tier Applications and LINQ to SQL

Summary

17 Introducing ADO.NET 3.0 and the Entity Framework

Understanding the General Nature of the Problem and the Solution

Understanding Problems with the Relational Database Model as It Pertains to C# Programmers

Understanding How the Entity Framework Is Designed to Help

Grokking the Nature of the Solution

Finding Additional Resources

Wikipedia

Entity SQL Blog

Downloading and Installing the Entity Framework

Downloading Samples

Go Live Estimate

Building a Sample Application Using Vanilla ADO.NET Programming

Defining a Database for Storing Stock Quotes

Adding a Stored Procedure for Inserting Quotes

Adding a Foreign Key

Reference: The Complete Sample Database Script

Writing Code to Obtain the Stock Quotes and Update the Database

Programming with the Entity Framework

Creating the Entity Data Model

Adding an Association

Querying the Entity Data Model with Entity SQL

Querying the Entity Data Model with LINQ to Entities

Doing It All with LINQ

Summary

Part IV LINQ for XML

18 Extracting Data from XML

Loading XML Documents

Querying XML Documents

Using XDocument

Using XElement

Managing Attributes

Loading XML from a String

Handling Missing Data

Using Query Expressions with XML Data

Using Namespaces

Nesting Queries

Filtering with Where Clauses

Finding Elements Based on Context

Sorting XML Queries

Calculating Intermediate Values with Let

Annotating Nodes

Summary

19 Comparing LINQ to XML with Other XML Technologies

Comparing LINQ to XML with XPath

Using Namespaces

Finding Children

Finding Siblings

Filtering Elements

Comparing LINQ to XML Transformations with XSLT

Transforming XML Data Using Functional Construction

Summary

20 Constructing XML from Non-XML Data

Constructing XML from CSV Files

Generating Text Files from XML

Using XML and Embedded LINQ Expressions (in VB)

Summary

21 Emitting XML with the XmlWriter

Exploring the XmlWriter, Quickly

Using XmlTextWriter to Write an XML File

Summary

22 Combining XML with Other Data Models

Creating XML from SQL Data

Defining the Object-Relational Map

Constructing the XML Document from the SQL Data

Using the XComment Node Type

Displaying the XML Document in a TreeView

Updating SQL Data from XML

Summary

23 LINQ to XSD Supports Typed XML Programming

Understanding the Basic Design Goals of LINQ to XSD

Programming with LINQ to XSD

Downloading and Installing the LINQ to XSD Preview

Creating a LINQ to XSD Preview Console Application

Defining the XML Context

Defining the XML Schema File

Adding a Regular Expression to a Schema File

Querying with LINQ to XML for Objects

Summary

Index

Foreword

Data affects just about every aspect of our lives. Everything we do is analyzed, scrutinized, and delivered back to us in the form of coupons and other marketing materials. When you write an application, you can be sure that data in one form or another will be part of the solution. As software developers, the ease with which we can store, retrieve, and analyze data is crucial to our ability to develop compelling applications. Add to that the fact that data can come in a number of different shapes and formats, and it quickly comes to light that there is tremendous value in a consistent framework for accessing many types of data.

Several different data access approaches have been developed for Windows developers over the years. ADO and OLEDB and subsequently ADO.NET gave us universal access to relational databases. MSXML and ADO.NET made it possible to inspect and manipulate XML documents. Each of these technologies had their benefits and drawbacks, but one common thread ran through each of them: They failed to deliver data access capabilities in a way that felt natural to developers.

LINQ now makes data access a first-class programming concept in .NET, making it possible for developers to express queries in a way that makes sense to developers. What makes LINQ unique is that it enables programmers to create type-safe data access code complete with Intellisense support and compile time syntax checking.

Paul Kimmel has done an excellent job of presenting LINQ in a concise and complete manner. Not only has he made LINQ approachable, but he has also masterfully explained concepts such as Anonymous Types and Lambda Expressions that help make LINQ a reality. The sample code throughout the book demonstrates the application of the technology in a clear and meaningful way. This is a great “Saturday morning with a pot of coffee” kind of book. I hope you’ll dive in and get as much out of this book as I did.

Darryl Hogan
Architect Evangelist, Microsoft

About the Author

Paul Kimmel is a four-time Microsoft MVP, the author of over a dozen books on object-oriented programming and UML, including three books on Microsoft .NET, a columnist for codeguru.com, developer.com, informit.com, devsource.com, and devx.com, a cofounder of the Greater Lansing Area .NET Users Group (glugnet.org, East Lansing and Flint), a full-time software developer, and sometimes pilot. Paul still lives and works in the greater Lansing, Michigan, area (and hasn’t given up on the economy). After 15 years of independent consulting, Paul now works for EDS as an application architect.

Dedication

This book is dedicated to the men and women of the United States armed forces, especially those brave souls serving in conflict zones, away from hearth and kin. To all military police men and women—Lookout Firefly it’s Night-train! Mohawk, 38 out.

Acknowledgments

Sometimes I read other people’s acknowledgements but a long list of names is boring unless it’s your name. If the casual reader is reading this, then you are helping me thank the myriad of people that make a book like this possible. If you are one of the people listed, then know that your able assistance is greatly appreciated.

Thanks to Neil Rowe, my acquisitions editor; Curt Johnson, marketing manager at Pearson; and Joan Murray, editor, also at Pearson. I wrote slower but finishing a book is thrilling.

Thanks to Joe Kunk for not complaining about how much work technical editing is and actually testing the examples. Joe also does a lot of heavy lifting at Glugnet East Lansing and Flint (our .NET User Groups). Thanks to the rest of the glugnet board for covering for me in my absence: Vivek Joshi, Alireza Namvar, Eric Vogel, Jeff McWherter, Vijay Jagdale, Jason Harris, Aaron Lilywhite, and Rich Hamilton.

Thanks to Bart De Smet from Microsoft for assistance with the Active Directory IQueryable provider—LINQ to AD is cool. Thanks to Daryl Hogan for the foreword.

I’d also like to mention Brian Dawson, Brad Jones, Tyler Durden, Jackson Wayfare, Blizzard for War Craft and Rockstar games for GTA IV, my kids Alex and Noah, Dena and Joe Swanson (for wine and comic relief), Ed Swanson for cigars, and all of the great folks at Pearson behind the scenes that turn my six-fingered manuscript into a shiny new book.

We Want to Hear from You!

As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way.

You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book’s title and author, as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book.

E-mail:        [email protected]

Mail:           Neil Rowe
                  Executive Editor
                  Sams Publishing
                  800 East 96th Street
                  Indianapolis, IN 46240 USA

Reader Services

Visit our website and register this book at www.informit.com/register for convenient access to any updates, downloads, or errata that might be available for this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.200.14