Table Of ContentPro LINQ
Language Integrated Query in C#
2010
■ ■ ■
Adam Freeman and Joseph C. Rattz, Jr.
■ CONTENTS
Pro LINQ: Language Integrated Query in C# 2010
Copyright © 2010 by Adam Freeman and Joseph C. Rattz, Jr.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-2653-6
ISBN-13 (electronic): 978-1-4302-2654-3
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only
in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Technical Reviewer: Fabio Claudio Ferracchiati
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes,
Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft,
Matt Wade, Tom Welsh
Coordinating Editor: Mary Tobin
Copy Editor: Kim Wimpsett
Compositor: Bronkella Publishing LLC
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street,
6th Floor,New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-
ny@springer-sbm.com, or visitwww.springeronline.com.
For information on translations, please e-mailrights@apress.com, or visitwww.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers atwww.apress.com. You will need to answer
questions pertaining to this book in order to successfully download the code.
ii
■ CONTENTS
Dedicated to my wife, Jacqui Griffyth
—Adam Freeman
For my parents, Joe and Josie Rattz, that believed I could do anything and encouraged me to
believe the same. Thank you.
—Joseph C. Rattz, Jr.
iii
■ CONTENTS
Contents at a Glance
Contents at a Glance ..........................................................................iv
Contents ...........................................................................................vi
About the Author............................................................................... xx
About the Technical Reviewer ........................................................... xxi
Acknowledgments........................................................................... xxii
Part 1: Pro LINQ: Language Integrated Query in C# 2010.........................1
■Chapter 1: Hello LINQ .......................................................................3
■Chapter 2: C# Language Enhancements for LINQ ...............................21
Part 2: LINQ to Objects ......................................................................55
■Chapter 3: LINQ to Objects Introduction............................................57
■Chapter 4: Deferred Operators.........................................................69
■Chapter 5: Nondeferred Operators.................................................. 151
Part 3: LINQ to XML......................................................................... 211
■Chapter 6: LINQ to XML Introduction .............................................. 213
■Chapter 7: The LINQ to XML API ..................................................... 219
■Chapter 8: LINQ to XML Operators.................................................. 313
■Chapter 9: Additional XML Capabilities........................................... 345
Part 4: LINQ to DataSet.................................................................... 387
■Chapter 10: LINQ to DataSet Operators........................................... 389
■Chapter 11: Additional DataSet Capabilities.................................... 427
Part 5: LINQ to SQL ...........................................................................55
■Chapter 12: LINQ to SQL Introduction ............................................. 437
iv
■ CONTENTS
■Chapter 13: LINQ to SQL Tips and Tools.......................................... 449
■Chapter 14: LINQ to SQL Database Operations................................. 475
■Chapter 15: LINQ to SQL Entity Classes .......................................... 521
■Chapter 16: The LINQ to SQL DataContext ....................................... 569
■Chapter 17: LINQ to SQL Concurrency Conflicts............................... 635
■Chapter 18: Additional LINQ to SQL Capabilities .............................. 653
Part 6: LINQ to Entities.................................................................... 665
■Chapter 19: LINQ to Entities Introduction........................................ 667
■Chapter 20: LINQ to Entities Operations.......................................... 679
■Chapter 21: LINQ to Entities Classes .............................................. 723
Part 7: Parallel LINQ..........................................................................55
■Chapter 22: Parallel LINQ Introduction ........................................... 751
■Chapter 23: Using Parallel LINQ..................................................... 757
■Chapter 24: Parallel LINQ Operators............................................... 773
Index ............................................................................................. 795
v
■ CONTENTS
Contents
Contents at a Glance ..........................................................................iv
Contents ...........................................................................................vi
About the Author............................................................................... xx
About the Technical Reviewer ........................................................... xxi
Acknowledgments........................................................................... xxii
Part 1: Pro LINQ: Language Integrated Query in C# 2010.........................1
■Chapter 1: Hello LINQ .......................................................................3
A Paradigm Shift.............................................................................................................3
Query XML.............................................................................................................................................4
Query a SQL Server Database................................................................................................................5
Introduction.....................................................................................................................7
LINQ Is About Data Queries....................................................................................................................7
How to Obtain LINQ................................................................................................................................8
LINQ Is Not Just for Queries............................................................................................8
Tips to Get You Started.................................................................................................12
Use the var Keyword When Confused..................................................................................................12
Use the Cast or OfType Operators for Legacy Collections.....................................................................................14
The OfType Operator versus the Cast Operator...................................................................................15
Don’t Assume a Query Is Bug-Free......................................................................................................15
Take Advantage of Deferred Queries...................................................................................................16
Use the DataContext Log.....................................................................................................................17
Use the LINQ Forum.............................................................................................................................18
Summary......................................................................................................................18
vi
■ CONTENTS
■Chapter 2: C# Language Enhancements for LINQ ...............................21
C# Language Additions.................................................................................................21
Lambda Expressions..............................................................................................................................................22
Expression Trees...................................................................................................................................................27
Keyword var, Object Initialization, and Anonymous Types....................................................................................28
Extension Methods................................................................................................................................................33
Partial Methods.....................................................................................................................................................39
Query Expressions.................................................................................................................................................41
Summary......................................................................................................................52
Part 2: LINQ to Objects ......................................................................55
■Chapter 3: LINQ to Objects Introduction............................................57
LINQ to Objects Overview.............................................................................................57
IEnumerable<T>, Sequences, and the Standard Query Operators...............................58
Returning IEnumerable<T>, Yielding, and Deferred Queries.......................................59
Func Delegates.............................................................................................................62
The Standard Query Operators Alphabetical Cross-Reference.....................................64
A Tale of Two Syntaxes.................................................................................................66
Summary......................................................................................................................66
■Chapter 4: Deferred Operators.........................................................69
Referenced Namespaces..............................................................................................69
Referenced Assemblies................................................................................................69
Common Classes..........................................................................................................69
The Deferred Operators by Purpose.............................................................................71
Restriction...........................................................................................................................................71
Projection.............................................................................................................................................74
Partitioning..........................................................................................................................................85
Concatenation........................................................................................................................................................93
Ordering.................................................................................................................................................................96
Join......................................................................................................................................................................116
vii
■ CONTENTS
Grouping..............................................................................................................................................................120
Set.......................................................................................................................................................................126
Conversion.........................................................................................................................................133
Element..............................................................................................................................................140
Generation.........................................................................................................................................145
Summary....................................................................................................................148
■Chapter 5: Nondeferred Operators.................................................. 151
Referenced Namespaces............................................................................................151
Common Classes........................................................................................................151
The Nondeferred Operators by Purpose.....................................................................154
Conversion...........................................................................................................................................................155
Equality................................................................................................................................................................168
Element................................................................................................................................................................172
Quantifiers...........................................................................................................................................................187
Aggregate............................................................................................................................................................193
Summary....................................................................................................................209
Part 3: LINQ to XML......................................................................... 211
■Chapter 6: LINQ to XML Introduction .............................................. 213
Introduction.................................................................................................................215
Cheating the W3C DOM XML API.................................................................................216
Summary....................................................................................................................217
■Chapter 7: The LINQ to XML API ..................................................... 219
Referenced Namespaces............................................................................................219
Significant API Design Enhancements........................................................................219
XML Tree Construction Simplified with Functional Construction......................................................220
Document Centricity Eliminated in Favor of Element Centricity........................................................222
Names, Namespaces, and Prefixes...................................................................................................224
Node Value Extraction.......................................................................................................................227
The LINQ to XML Object Model...................................................................................230
viii
■ CONTENTS
Deferred Query Execution, Node Removal, and the Halloween Problem....................231
XML Creation..............................................................................................................234
Creating Elements with XElement.....................................................................................................234
Creating Attributes with XAttribute....................................................................................................237
Creating Comments with XComment.................................................................................................238
Creating Containers with XContainer.................................................................................................238
Creating Declarations with XDeclaration...........................................................................................239
Creating Document Types with XDocumentType...............................................................................240
Creating Documents with XDocument.................................................................................................................241
Creating Names with XName.............................................................................................................242
Creating Namespaces with XNamespace..........................................................................................243
Creating Nodes with XNode.................................................................................................................................243
Creating Processing Instructions with XProcessingInstruction.........................................................243
Creating Streaming Elements with XStreamingElement...................................................................246
Creating Text with XText....................................................................................................................247
Creating CData with XCData................................................................................................................................248
XML Output.................................................................................................................248
Saving with XDocument.Save()..........................................................................................................248
Saving with XElement.Save()...............................................................................................................................250
XML Input....................................................................................................................251
Loading with XDocument.Load()........................................................................................................251
Loading with XElement.Load()...........................................................................................................253
Parsing with XDocument.Parse() or XElement.Parse()......................................................................254
XML Traversal.............................................................................................................254
Traversal Properties..........................................................................................................................255
Traversal Methods.............................................................................................................................260
XML Modification........................................................................................................276
Adding Nodes......................................................................................................................................................276
Deleting Nodes..................................................................................................................................281
Updating Nodes.................................................................................................................................284
ix
■ CONTENTS
XElement.SetElementValue() on Child XElement Objects..................................................................289
XML Attributes............................................................................................................290
Attribute Creation................................................................................................................................................291
Attribute Traversal.............................................................................................................................291
Attribute Modification........................................................................................................................295
XML Annotations.........................................................................................................300
Adding Annotations with XObject.AddAnnotation()............................................................................300
Accessing Annotations with XObject.Annotation() or XObject.Annotations().......................................................300
Removing Annotations with XObject.RemoveAnnotations()................................................................................301
Annotations Example...........................................................................................................................................301
XML Events.................................................................................................................304
XObject.Changing..............................................................................................................................305
XObject.Changed...............................................................................................................................305
A Couple of Event Examples..............................................................................................................306
Trick or Treat, or Undefined?.............................................................................................................310
Summary....................................................................................................................310
■Chapter 8: LINQ to XML Operators.................................................. 313
Introduction to LINQ to XML Operators.......................................................................313
Ancestors....................................................................................................................314
Prototypes............................................................................................................................................................314
Examples...........................................................................................................................................314
AncestorsAndSelf.......................................................................................................319
Prototypes............................................................................................................................................................319
Examples...........................................................................................................................................319
Attributes....................................................................................................................322
Prototypes............................................................................................................................................................322
Examples...........................................................................................................................................322
DescendantNodes.......................................................................................................324
Prototypes............................................................................................................................................................324
Examples...........................................................................................................................................325
x