ebook img

LINQ pocket reference PDF

168 Pages·2008·0.543 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview LINQ pocket reference

LINQ Pocket Reference Joseph Albahari and Ben Albahari Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo LINQ Pocket Reference by Joseph Albahari and Ben Albahari Copyright © 2008 Joseph Albahari and Ben Albahari. All rights reserved. Printed in Canada. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/ institutional sales department: (800) 998-9938 [email protected]. Editor: Laurel R.T. Ruma Cover Designer: Karen Montgomery Production Editor: Loranah Dimant Interior Designer: David Futato Proofreader: Loranah Dimant Illustrator: Robert Romano Indexer: Julie Hawks Printing History: February 2008: First Edition. NutshellHandbook,theNutshellHandbooklogo,andtheO’Reillylogoare registered trademarks of O’Reilly Media, Inc. ThePocket Reference series designations,LINQPocketReference,theimageofthehornedscreamer,and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish theirproductsareclaimedastrademarks.Wherethosedesignationsappear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. .NET is a registered trademark of Microsoft Corporation. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-0-596-51924-7 [TM] Contents Getting Started 1 Lambda Queries 4 Chaining Query Operators 4 Composing Lambda Expressions 6 Natural Ordering 9 Other Operators 9 Comprehension Queries 10 Iteration Variables 12 Query Syntax Versus SQL Syntax 13 Query Syntax Versus Lambda Syntax 13 Mixed Syntax Queries 14 Deferred Execution 15 Reevaluation 16 Outer Variables 17 How Deferred Execution Works 17 Chaining Decorators 19 How Queries Are Executed 20 Subqueries 22 Subqueries and Deferred Execution 25 Composition Strategies 25 Progressive Query Building 25 The into Keyword 27 Wrapping Queries 28 Projection Strategies 30 Object Initializers 30 Anonymous Types 30 The let Keyword 32 Interpreted Queries 33 How Interpreted Queries Work 35 AsEnumerable 38 LINQ to SQL 40 LINQ to SQL Entity Classes 40 DataContext 42 Automatic Entity Generation 45 Associations 45 Deferred Execution with LINQ to SQL 47 DataLoadOptions 48 Updates 50 Building Query Expressions 52 Delegates Versus Expression Trees 53 Expression Trees 55 Query Operator Overview 59 Filtering 62 Where 63 Take and Skip 65 TakeWhile and SkipWhile 65 Distinct 66 Projecting 66 Select 67 SelectMany 72 Joining 82 Join and GroupJoin 83 Ordering 92 OrderBy, OrderByDescending, ThenBy, ThenByDescending 92 Grouping 95 GroupBy 96 Set Operators 100 Concat and Union 100 Intersect and Except 100 Conversion Methods 101 OfType and Cast 101 ToArray, ToList, ToDictionary, ToLookup 103 AsEnumerable and AsQueryable 104 Element Operators 104 First, Last, Single 105 ElementAt 106 DefaultIfEmpty 107 Aggregation Methods 107 Count and LongCount 107 Min and Max 108 Sum and Average 109 Aggregate 110 Quantifiers 111 Contains and Any 111 All and SequenceEqual 112 Generation Methods 112 Empty 112 Range and Repeat 113 LINQ to XML 113 Architectural Overview 114 X-DOM Overview 115 Loading and Parsing 117 Saving and Serializing 118 Instantiating an X-DOM 118 Functional Construction 119 Specifying Content 120 Automatic Deep Cloning 121 Navigating/Querying an X-DOM 122 Child Node Navigation 122 Parent Navigation 126 Peer Node Navigation 127 Attribute Navigation 128 Updating an X-DOM 128 Simple Value Updates 128 Updating Child Nodes and Attributes 129 Updating Through the Parent 130 Working with Values 133 Setting Values 133 Getting Values 133 Values and Mixed Content Nodes 135 Automatic XText Concatenation 136 Documents and Declarations 136 XDocument 136 XML Declarations 139 Names and Namespaces 140 Specifying Namespaces in the X-DOM 142 The X-DOM and Default Namespaces 143 Prefixes 145 Projecting into an X-DOM 147 Eliminating Empty Elements 149 Streaming a Projection 150 Transforming an X-DOM 151 Index 153 LINQ Pocket Reference LINQ, or Language Integrated Query, allows you to write structuredtype-safequeriesoverlocalobjectcollectionsand remotedatasources.ItisanewfeatureofC#3.0and.NET Framework 3.5. LINQ lets you query any collection implementing IEnumerable<>,whetheranarray,list,XMLDOM,orremote datasource(suchasatableinSQLServer).LINQoffersthe benefits of both compile-time type checking and dynamic query composition. ThecoretypesthatsupportLINQaredefinedintheSystem. LinqandSystem.Linq.ExpressionsnamespacesintheSystem. Core assembly. NOTE TheexamplesinthisbookmirrortheexamplesinChap- ters 8–10 of C# 3.0 in a Nutshell (O’Reilly) and are pre- loaded into an interactive querying tool called LINQPad. You can download LINQPad fromhttp://www.linqpad.net/. Getting Started ThebasicunitsofdatainLINQaresequencesandelements. A sequence is any object that implements the generic IEnumerable interface, and an element is each item in the sequence.Inthefollowingexample,namesisasequence,and Tom,Dick, andHarry are elements: 1 string[] names = { "Tom", "Dick", "Harry" }; We call such a sequence a local sequence because it repre- sents a local collection of objects in memory. A query operator is a method that transforms a sequence. A typicalqueryoperatoracceptsaninputsequenceandemitsa transformed output sequence. In the Enumerable class in System.Linq,therearearound40queryoperators,allimple- mented as static extension methods, called standard query operators. NOTE LINQalsosupportssequencesthatcanbedynamicallyfed fromaremotedatasourcesuchasaSQLServer.Thesese- quences additionally implement the IQueryable<> inter- faceandaresupportedthroughamatchingsetofstandard queryoperatorsintheQueryableclass.Formoreinforma- tion, see the upcoming “Interpreted Queries” section. A query is an expression that transforms sequences with query operators. The simplest query comprises one input sequence and one operator. For instance, we can apply the Where operator on a simple array to extract those whose length is at least four characters as follows: string[] names = { "Tom", "Dick", "Harry" }; IEnumerable<string> filteredNames = System.Linq.Enumerable.Where ( names, n => n.Length >= 4); foreach (string n in filteredNames) Console.Write (n + "|"); // Dick|Harry| Because the standard query operators are implemented as extension methods, we can call Where directly on names—as though it were an instance method: IEnumerable<string> filteredNames = names.Where (n => n.Length >= 4); 2 | LINQ Pocket Reference For this to compile, you must import the System.Linq namespace. Here’s a complete example: using System; using System.Linq; class LinqDemo { static void Main() { string[] names = { "Tom", "Dick", "Harry" }; IEnumerable<string> filteredNames = names.Where (n => n.Length >= 4); foreach (string name in filteredNames) Console.Write (name + "|"); } } // RESULT: Dick|Harry| NOTE If you are unfamiliar with C#’s lambda expressions, ex- tension methods, or implicit typing, visit www.albahari. com/cs3primer. We can further shorten our query by implicitly typing filteredNames: var filteredNames = names.Where (n => n.Length >= 4); Mostqueryoperatorsacceptalambdaexpressionasanargu- ment. The lambda expression helps guide and shape the query. In our example, the lambda expression is as follows: n => n.Length >= 4 Theinputargumentcorrespondstoaninputelement.Inthis case,theinputargumentnrepresentseachnameinthearray and is of type string. The Where operator requires that the lambda expression return a bool value, which if true, indi- cates that the element should be included in the output sequence. Getting Started | 3

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.