www.it-ebooks.info Paul Kimmel LINQ U N L E A S H E D C # for 800 East 96th Street,Indianapolis,Indiana 46240 USA www.it-ebooks.info LINQ Unleashed for C# Editor-in-Chief Copyright © 2009 by Pearson Education,Inc. Karen Gettman All rights reserved. No part of this book shall be reproduced,stored in a retrieval Executive Editor system,or transmitted by any means,electronic,mechanical,photocopying,recording, or otherwise,without written permission from the publisher. No patent liability is Neil Rowe assumed with respect to the use of the information contained herein. Although every Development Editor precaution has been taken in the preparation of this book,the publisher and author assume no responsibility for errors or omissions. Nor is any liability assumed for Mark Renfrow damages resulting from the use of the information contained herein. Managing Editor ISBN-13: 978-0-672-32983-8 Kristy Hart ISBN-10: 0-672-32983-2 Project Editor Library of Congress Cataloging-in-Publication Data Betsy Harris Copy Editor Kimmel,Paul. Karen Annett LINQ unleashed for C# / Paul Kimmel. — 1st ed. p. cm. Indexers Lisa Stumpf ISBN 978-0-672-32983-8 Publishing Works 1. C# (Computer program language) 2. Microsoft LINQ. I. Title. QA76.73.C154K5635 2009 Proofreader 005.13’3—dc22 Linda Seifer 2008030703 Technical Editor Printed in the United States of America Joe Kunk First Printing August 2008 Publishing Coordinator Cindy Teeters Trademarks Cover Designer All terms mentioned in this book that are known to be trademarks or service marks Gary Adair 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 Compositor validity of any trademark or service mark. Jake McFarland Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possi- ble,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] www.it-ebooks.info Contents at a Glance Introduction...................................................................................1 Part I Getting Ready for LINQ 1 Programming with Anonymous Types.................................................5 2 Using Compound Type Initialization.................................................29 3 Defining Extension and Partial Methods............................................61 4 yield return: Using .NET’s State Machine Generator.............................85 5 Understanding Lambda Expressions and Closures................................97 6 Using Standard Query Operators.....................................................121 Part II LINQ for Objects 7 Sorting and Grouping Queries........................................................137 8 Using Aggregate Operations...........................................................151 9 Performing Set Operations.............................................................167 10 Mastering Select and SelectMany.....................................................185 11 Joining Query Results....................................................................211 12 Querying Outlook and Active Directory...........................................239 Part III LINQ for Data 13 Querying Relational Data with LINQ...............................................265 14 Creating Better Entities and Mapping Inheritance and Aggregation.......289 15 Joining Database Tables with LINQ Queries ......................................309 16 Updating Anonymous Relational Data.............................................349 17 Introducing ADO.NET 3.0 and the Entity Framework.........................383 Part IV LINQ for XML 18 Extracting Data from XML.............................................................415 19 Comparing LINQ to XML with Other XML Technologies....................437 20 Constructing XML from Non-XML Data...........................................453 21 Emitting XML with the XmlWriter..................................................463 22 Combining XML with Other Data Models........................................469 23 LINQ to XSD Supports Typed XML Programming..............................485 Index.........................................................................................499 www.it-ebooks.info Table of Contents Introduction 1 Conventions Used in This Book.........................................................2 Part I Getting Ready for LINQ 1 Programming with Anonymous Types 5 Understanding Anonymous Types......................................................6 Programming with Anonymous Types.................................................7 Defining Simple Anonymous Types.............................................7 Using Array Initializer Syntax.....................................................7 Creating Composite Anonymous Types.......................................9 Using Anonymous Type Indexes in For Statements......................12 Anonymous Types and Using Statements...................................14 Returning Anonymous Types from Functions..............................17 Databinding Anonymous Types........................................................18 Testing Anonymous Type Equality....................................................23 Using Anonymous Types with LINQ Queries......................................24 Introducing Generic Anonymous Methods.........................................25 Using Anonymous Generic Methods..........................................26 Implementing Nested Recursion...............................................27 Summary......................................................................................28 2 Using Compound Type Initialization 29 Initializing Objects with Named Types...............................................30 Implementing Classes for Compound Initialization Through Named Types.......................................................................32 Understanding Auto-Implemented Properties..............................34 Initializing Anonymous Types..........................................................34 Initializing Collections....................................................................36 Finishing the Hypergraph........................................................39 Implementing the Hypergraph Controls Using the Observer Pattern...............................................................................47 Using Conversion Operators............................................................51 ToArray................................................................................51 OfType.................................................................................54 Cast.....................................................................................54 AsEnumerable........................................................................55 www.it-ebooks.info Contents v ToList...................................................................................56 ToDictionary.........................................................................57 ToLookup..............................................................................58 Summary......................................................................................60 3 Defining Extension and Partial Methods 61 Extension Methods and Rules of the Road..........................................61 Defining Extension Methods............................................................64 Implementing Extension Methods............................................64 Overloading Extension Methods...............................................67 Defining Generic Extension Methods.........................................69 How Extension Methods Support LINQ.............................................73 Implementing a “Talking” String Extension Method............................78 Defining Partial Methods.................................................................79 Summary......................................................................................84 4 yield return: Using .NET’s State Machine Generator 85 Understanding How yield return Works.............................................86 Using yield return and yield break....................................................88 Profiling Code.......................................................................93 Using yield break...................................................................95 Summary......................................................................................95 5 Understanding Lambda Expressions and Closures 97 Understanding the Evolution from Function Pointers to Lambda Expressions.................................................................................98 Writing Basic Lambda Expressions...................................................101 Automatic Properties.............................................................102 Reading Lambda Expressions..................................................103 Lambda Expressions Captured as Generic Actions......................104 Searching Strings..................................................................106 Lambda Expressions Captured as Generic Predicates...................108 Binding Control Events to Lambda Expressions.........................109 Dynamic Programming with Lambda Expressions..............................110 Using Select<T> with Lambda Expressions................................110 Using Where<T> with Lambda Expressions...............................112 Using OrderBy<T> with Lambda Expressions.............................113 Compiling Lambda Expressions as Code or Data........................114 Lambda Expressions and Closures...................................................117 Currying.....................................................................................119 Summary....................................................................................120 www.it-ebooks.info vi LINQ Unleashed 6 Using Standard Query Operators 121 Understanding How LINQ Is Implemented.......................................121 Constructing a LINQ Query...........................................................122 Filtering Information....................................................................122 Using Quantifiers.........................................................................124 Partitioning with Skip and Take......................................................126 Using Generation Operations.........................................................127 DefaultIfEmpty.....................................................................127 Empty.................................................................................127 Range.................................................................................127 Repeat................................................................................128 Equality Testing...........................................................................129 Obtaining Specific Elements from a Sequence...................................131 Appending Sequences with Concat..................................................132 Summary....................................................................................133 Part II LINQ for Objects 7 Sorting and Grouping Queries 137 Sorting Information......................................................................137 Sorting in Ascending and Descending Order .............................138 Sort in Descending Order Using the Extension Method Directly...140 Performing Secondary Sorts....................................................141 Reversing the Order of Items..................................................144 Grouping Information...................................................................145 Summary....................................................................................150 8 Using Aggregate Operations 151 Aggregating.................................................................................151 Averaging Collection Values...........................................................154 Counting Elements.......................................................................157 Finding Minimum and Maximum Elements......................................157 Summing Query Results ................................................................162 Median: Defining a Custom Aggregation Operation...........................163 Summary....................................................................................165 9 Performing Set Operations 167 Finding Distinct Elements..............................................................167 Finding Distinct Objects Using Object Fields.............................169 Defining Exclusive Sets with Intersect and Except..............................177 Creating Composite Resultsets with Union.......................................182 Summary....................................................................................184 www.it-ebooks.info Contents vii 10 Mastering Select and SelectMany 185 Exploring Select...........................................................................185 Selecting with Function Call Effects.........................................186 Manipulating Select Predicates................................................190 Returning Custom Business Objects from a Data Access Layer......190 Using Select Indexes to Shuffle (or Unsort) an Array...................194 Forming the Basis of a Card Game Like Blackjack.......................195 Projecting New Types from Calculated Values............................200 Importing DLLs....................................................................200 Using GDI+ with Windows API (or External DLL) Methods..........201 Using Select to I-Cap Words...................................................201 Projecting New Types from Multiple Sources.....................................203 Creating a New Sequence from Multiple Sequences with SelectMany....205 Using SelectMany with Indexes......................................................207 Summary....................................................................................209 11 Joining Query Results 211 Using Multiple From Clauses..........................................................211 Defining Inner Joins.....................................................................213 Using Custom, or Nonequijoins......................................................214 Defining a Nonequal Custom Join...........................................215 Defining a Custom Join with Multiple Predicates.......................219 Defining Custom Joins with a Temporary Range Variable............220 Implementing Group Join and Left Outer Join..................................224 Defining a Group Join...........................................................224 Implementing a Left Outer Join..............................................226 Implementing a Cross Join.............................................................228 Defining Joins Based on Composite Keys..........................................237 Summary....................................................................................237 12 Querying Outlook and Active Directory 239 LINQ to Outlook..........................................................................239 Querying Active Directory with Straight C# Code..............................243 LINQ to Active Directory...............................................................245 Creating an IQueryable LINQ Provider.....................................245 Implementing the IQueryProvider...........................................246 Defining Active Directory as the Data Source.............................248 Converting a LINQ Query to an Active Directory Query..............252 Implementing Helper Attributes..............................................257 Defining Active Directory Schema Entities................................259 Querying Active Directory with LINQ..............................................260 Summary....................................................................................262 www.it-ebooks.info viii LINQ Unleashed Part III LINQ for Data 13 Querying Relational Data with LINQ 265 Defining Table Objects..................................................................266 Mapping Classes to Tables......................................................269 Viewing the Query Text Generated by LINQ..............................273 Connecting to Relational Data with DataContext Objects...................275 Querying DataSets........................................................................277 Selecting Data from a DataTable..............................................278 Querying the DataTable with a Where Clause............................280 Using Partitioning Methods....................................................282 Sorting Against DataTables.....................................................282 Defining a Join with DataSets.................................................282 SqlMetal: Using the Entity Class Generator Tool................................285 Using the LINQ to SQL Class Designer.............................................285 Summary....................................................................................287 14 Creating Better Entities and Mapping Inheritance and Aggregation 289 Defining Better Entities with Nullable Types.....................................289 Mapping Inheritance Hierarchies for LINQ to SQL.............................294 Creating Inheritance Mappings with the LINQ to SQL Designer...298 Customizing Classes Created with the LINQ to SQL Designer.......299 Adding EntitySet Classes as Properties..............................................300 Creating Databases with LINQ to SQL..............................................305 Summary....................................................................................308 15 Joining Database Tables with LINQ Queries 309 Defining Joins with LINQ to DataSet...............................................310 Coding Equijoins..................................................................310 Coding Nonequijoins............................................................312 Defining a Left Join and a Word about Right Joins.....................313 Considering Right Joins.........................................................315 Defining Joins with LINQ to SQL....................................................317 Coding Equijoins..................................................................317 Implementing the Group Join.................................................321 Implementing a Left Join.......................................................331 Querying Views with LINQ............................................................340 Building a View in SQL Server.................................................340 Querying a View with LINQ to SQL.........................................342 Databinding with LINQ to SQL.......................................................345 Summary....................................................................................347 www.it-ebooks.info Contents ix 16 Updating Anonymous Relational Data 349 Adding and Removing Data...........................................................349 Inserting Data with LINQ to SQL.............................................349 Deleting Data with LINQ to SQL.............................................352 Updating Data with LINQ to SQL............................................354 Using Stored Procedures.........................................................355 Calling User-Defined Functions......................................................363 Using Transactions.......................................................................366 Understanding Conflict Resolution..................................................368 Indicating the Conflict Handling Mode for SubmitChanges.........369 Catching and Resolving Concurrency Conflicts.........................371 N-Tier Applications and LINQ to SQL..............................................376 Summary....................................................................................382 17 Introducing ADO.NET 3.0 and the Entity Framework 383 Understanding the General Nature of the Problem and the Solution.....384 Understanding Problems with the Relational Database Model as It Pertains to C# Programmers.................................384 Understanding How the Entity Framework Is Designed to Help....385 Grokking the Nature of the Solution........................................385 Finding Additional Resources.........................................................386 Wikipedia............................................................................387 Entity SQL Blog....................................................................387 Downloading and Installing the Entity Framework.....................387 Downloading Samples...........................................................388 Go Live Estimate..................................................................388 Building a Sample Application Using Vanilla ADO.NET Programming...389 Defining a Database for Storing Stock Quotes............................389 Adding a Stored Procedure for Inserting Quotes.........................390 Adding a Foreign Key............................................................393 Reference: The Complete Sample Database Script.......................394 Writing Code to Obtain the Stock Quotes and Update the Database......................................................................397 Programming with the Entity Framework.........................................401 Creating the Entity Data Model ..............................................401 Adding an Association...........................................................402 Querying the Entity Data Model with Entity SQL.......................402 Querying the Entity Data Model with LINQ to Entities...............405 Doing It All with LINQ..................................................................406 Summary....................................................................................411 www.it-ebooks.info