LINQ in Action Ebook free dowwnload
LINQ in Action
LINQ in Action FABRICE MARGUERIE STEVE EICHERT JIM WOOLEY M A N N I N G
Greenwich (74° w. long.) For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact: Special Sales Department
Manning Publications Co. Sound View Court 3B fax: (609) 877-8256 Greenwich, CT 06830 email: [email protected]
©2008 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and ManningPublications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15% recycled and processed without the use of elemental chlorine.
Manning Publications Co. Copyeditor: Benjamin Berg Sound View Court 3B Typesetter: Gordan Salinovic Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1-933988-16-9 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 13 12 11 10 09 08
v
brief contents
10 ■
9 ■
8 ■
7 ■
6 ■
5 ■
4 ■
3 ■
2 ■
1 ■
11 ■
B R I E F C O N T E N T S
12 ■
13 ■
vii contents
C O N T E N T S
■
■
■
2.3 bject and collection initializers 52 ■
2.4 55 ■
■
2.5 64 ■
2.6 nonymous types 73
2.7 ummary 79
CONTENTS
■
■
■
■ ■
■
■
C O N T E N T S
■
■
■
■
■
CONTENTS
■
■
8.5 C O N T E N T S
■ ■
■ ■
■
■
10.5
CONTENTS
C O N T E N T S
■ ■
■
bonus chapter: Working with LINQ and DataSets available online only from www.manning.com/LINQinAction
foreword
It’s difficult for me to write this foreword, not because the road to LINQ was long and arduous or that I’m teary-eyed, wrought with emotion, or finding it difficult to compose just the right the words for a send-off worthy of a product that I’ve poured my very soul into. It’s difficult because I know that this is going to be a well-respected book and I’m finding it tricky to work in a punch line.
For me the LINQ project started years before anything official, back when I was involved in plotting and scheming over a new managed ADO . Back then, a few very smart developers had the audacity to suggest shucking off the chains of tradi- tional data access API s and designing around the ubiquity of objects and metadata that were fundamental to the new runtime—the Java runtime. Unfortunately, none of that happened. The traditionalists won, and at the time I was one of them. Yet what I gained from that experience was a perspective that data belongs
at the heart of any programming system, not bolted on as an afterthought. It made
sense that in a system based on objects, data should be objects too. But getting there was going to take overcoming a lot of challenges.
As an engineer, I was at the center of the advancements happening inside Microsoft, designing new API s and influencing language features that would move us forward. Many of these never made it all the way to shipping products, yet each attempt was a step in the right direction. LINQ is a culmination of these endeavors, of battles fought and lessons learned. It is born out of an accretion of insights from a group of my peers, draws upon existing theories and techniques from computer
xv F O R E W O R D
science at large, and would never have come together without the clear-cut wisdom and attention to detail that is Anders Hejlsberg.
Of course, there were all of you too. LINQ was shaped significantly by the com- munity of developers discussing it on forums and blogs. The ability to receive such immediate feedback was like turning on the lights in a darkened room. It was also energizing to watch as the spark caught fire in so many of you, how you became experts and evangelists, gave talks, wrote articles, and inspired each other.
That’s why this book is so important. Fabrice, Jim, and Steve were a large part of that community and have captured its essence within the pages of their book.
LINQ in Action is a book from the people to the people. It’s as if they had decided to throw a party for LINQ and everyone who’s anyone showed up.
So read on, enjoy, and don’t waste time waiting in line for the punch.
M ATT W ARREN P RINCIPAL A RCHITECT M
ICROSOFT
preface
I chose software development as the way to make a living mainly because it’s a technology that is constantly evolving. There’s always something new to learn. No chance of getting bored in this line of work! In addition to learning, I also enjoy
LINQ
teaching software development. Writing in Action was a good opportunity to both learn and teach at the same time.
When we started writing this book, LINQ was still an early prototype. We followed its evolution as it was taking shape. There was a lot to discover and a lot to under- stand. This is part of a software developer’s everyday job. We have to stay up-to-date with the technologies we use and learn new ones as they come out. The software development environment is evolving at an increasingly fast pace, and I don’t see any signs that that’s going to change.
. NET is a fast-moving environment. Over the last couple of years, we’ve seen two major releases of the . NET Framework, and several companion technologies have appeared: Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation, ASP.NET AJAX , Silverlight, and LINQ have joined our developer toolbox. Another trend in . NET is the multiplication of programming languages. F#, which will receive the same support as C# or
VB.NET
in Visual Studio, introduces functional programming in . NET . Dynamic lan- guages, such as Python and Ruby, are going to be supported by the . NET Dynamic Language Runtime.
xvii P R E F A C E
In coming years, we’ll have to deal with more programming languages than the ones we currently master. An advantage of C#, Visual Basic, and the other . NET languages is that they are constantly adapting. C# and
VB.NET have been
improved in their latest versions to offer support for language-integrated query- ing through LINQ .
In addition to offering novel approaches to deal with data, LINQ represents a shift toward declarative and functional programming. When people ask me for rea- sons to learn LINQ , I tell them that they should learn it in order to be able to use it with
XML , relational data, or in-memory collections, but above all to be able to start using declarative programming, deferred execution, and lambda expressions.
Start learning LINQ now! When you do, you’ll not only learn how to use this new technology, but you’ll also discover where programming is heading. One of
LINQ in Action was to help you fully comprehend the new
our main goals with approaches associated with LINQ .
F ABRICE M ARGUERIE
acknowledgments
Writing this book was a long process. It gave us the opportunity to have informative discussions with a lot of interesting people, as well as to learn and get input from some very smart individuals. We received help from many different sources—this book would not have been possible without them. Not only that: They also brought out the best in us. The people who contributed to the book in ways both large and small kept pushing us to raise the quality of our work higher and higher. We forgive them now for being so demanding. It was all for a good cause.
First, we’d like to express our gratitude to everyone at Manning. We appreci- ate the trust they placed in us and their involvement in asking us for our best in this project. A sincere thank-you to our publisher Marjan Bace for his vote of con- fidence in offering us the opportunity to write this book and to our editor Michael Stephens for being there throughout the process and helping make this project a reality.
Thanks to the editorial team at Manning who worked with us on turning this book into the end product you are now holding in your hands: Cynthia Kane, Mary Piergies, Karen Tegtmeyer, Ron Tomich, Lianna Wlasiuk, Megan Yockey, Benjamin Berg, Gordan Salinovic, Dottie Marsico, Elizabeth Martin, and Tiffany Taylor all guided us and kept us moving in the right direction.
We would also thank the many reviewers of the manuscript, who looked at it in various stages of development and whose thoughtful feedback made this a much better book: Dave Corun, Marius Bancila, Keith Farmer, Curt Christianson, Mark
xix A C K N O W L E D G M E N T S
Monster, Darren Neimke, Jon Skeet, Tomas Restrepo, Javier G. Lozano, Oliver Sturm, Mohammad Azam, Eric Swanson, Keith Hill, Rama Krishna Vavilala, and Bruno Boucard.
Our technical proofreader was Keith Farmer and he did a great job checking the code and making sure it all ran properly shortly before the book went to press. Thanks, Keith.
We’d also like to thank the people from Microsoft with whom we’ve been in touch: Keith Farmer, Dinesh Kulkarni, Amanda Silver, Erick Thompson, Matt Warren, and Eric White. Their hints and assistance were precious when we were lost in the mysteries of the early LINQ machinery. Special thanks to Matt Warren for agreeing to write the foreword to our book.
We can’t forget the subscribers to the Manning Early Access Program ( MEAP ) who reported errors either through the book’s forum or directly in emails, help- ing us weed out a lot of early mistakes. Michael Vandemore is one such vigilant reader we’d like to acknowledge here.
Thanks again to all of you listed above and below—as well as to any others we may have forgotten to mention: You made it possible!
ABRICE ARGUERIE F M
When Michael Stephens first contacted me, I knew that writing a book wasn’t an easy task, but I also knew that I was ready to take on the challenge. Only now, more than 20 months later, as I’m writing these acknowledgments, do I realize how big the challenge was and how much work was ahead of us.
I’d like to thank Jon Skeet, Troy Magennis, and Eric White for kindly allowing me to use parts of their work in my chapters. I’m grateful to my co-workers and friends who were kind enough to review portions of the manuscript and provided many useful comments. They include
Bruno Boucard, Pierrick Gourlain, Pierre Kovacs, Christophe Menet, and Patrick Smacchia.
Special thanks go to my wife for her patience during this long project. Who else could forgive me for all the extra time I spent in front of my computer during these last months?
Finally, I’d like to extend my thanks to Steve and Jim for their invaluable con- tributions to the book. They have been excellent partners. Steve and Jim, thank you for joining the project and bringing your talents to it.
A C K N O W L E D G M E N T S S TEVE E
ICHERT
I would like to thank my beautiful wife Christin, and three wonderful children, McKayla, Steven John, and Keegan. Your patience, encouragement, and love are what got me through this project. You continue to inspire me in ways that I never thought possible. Thank you!
IM W OOLEY J
I would like to thank Microsoft for their openness through blogs, forums, and access to tech previews. Without access to these, books like ours would not be pos- sible. I am also appreciative of the support we have received from members of the product teams, particularly Keith Farmer, Matt Warren, and Amanda Silver, as well as the evangelists like Doug Turnure and Joe Healy who support us out in the field and encourage us to do crazy things like write books.
Saving the best for last, I want to thank my family, particularly my wife Sindee, son Daniel, and my parents, who supported me even when it meant sacrificing holidays and weekends to meet publication deadlines. I couldn’t have done it without your patience and encouragement.
about this book LINQ in Action. This book is an introduction to the Microsoft .
Welcome to
NET LINQ technology and the rich toolset that comes with it.
IN tegrated Query. In a nutshell, it makes query opera- LINQ stands for Language
tions like SQL statements into first-class citizens in . NET languages like C# and VB .
LINQ offers built-in support for querying in-memory collections such as arrays or
lists,
XML , DataSets, and relational databases. But LINQ is extensible and can be used to query various data sources.
Our goal with this book is to help developers who have an existing knowledge of the . NET Framework and the C# or
VB.NET language to discover the concepts
introduced by LINQ and gain a complete understanding of how the technology works, as well as how to make the best of it in their projects.
LINQ in Action covers the entire LINQ spectrum. From Hello World code samples
and the new C# 3.0 and
VB.NET 9.0 features to LINQ ’s extensibility and a tour of all
the LINQ providers, this book has everything you need to get up to speed with LINQ and to be able to create applications that take advantage of it.
We believe this book provides the right mix of theory and examples. We made sure to keep the focus on the practical side of things, because we think that noth- ing’s better than a hands-on exploration of the technology. Several additions have been made to the C# and
VB.NET languages, as well as to the . NET class library. But
fear not: These language innovations aren’t difficult to grasp when you have the right code sample in front of you.
xxii
A B O U T T H I S B O O K
We’ll guide you along as you make your way through this new world where beasts like lambda expressions, query operators, and expression trees live. You’ll discover all the basics of LINQ that’ll help you form a clear understanding of the complete LINQ toolset. We’ll also provide a presentation of the common use cases for all the flavors of LINQ . Whether you want to use LINQ to query objects,
XML documents, or rela-
tional databases, you’ll find all the information you’ll need. But we won’t stop at the basic code. We’ll also show you how LINQ can be used for advanced data processing. This includes coverage of LINQ ’s extensibility, which allows us to query more data sources than those supported by default.
In order to base our code samples on concrete business classes, we’ll use a run- ning example. This example, LinqBooks, is a personal book-cataloging system. This means that the LINQ queries you’ll see throughout the book will deal with
Book Publisher Author
objects such as , , and . The running example we’ve chosen is broad enough to involve all aspects of LINQ . We’ll progressively build the sam- ple application throughout the chapters, finishing with a complete application in the last chapter.
Who should read this book
This book targets the . NET developer audience. Whether you don’t know much about LINQ yet or you already have a good knowledge of it, this book is for you.
In order to fully appreciate this book, you should already know C# or
VB.NET ,
ideally C# 2.0 or
VB.NET 8.0.
How the book is organized
This book has been written so that you can choose what you want to read and how you want to read it. It has 5 parts, 13 chapters, an appendix, a list of resources, and a bonus chapter.
LINQ
Part 1 introduces and its toolset. It also helps you to write your first LINQ queries. If LINQ is new to you or if you want to make sure that you have all the background information required to correctly understand LINQ code, the first part of this book is for you. If you’re already familiar with LINQ and have a firm grasp on the new features of C# 3.0 and
VB.NET 9.0, feel free to skip the first chap-
ters and jump directly to other parts of the book that are related to specific uses of
LINQ . If you want to understand where LINQ comes from, before you dive in, you may be interested in reading the bit of history we propose in chapter 1. A B O U T T H I S B O O K LINQ to Objects and querying in-memory collections. This
Part 2 is dedicated to part also contains information about common LINQ use cases and best practices that’ll be useful when working with any LINQ flavor.
LINQ SQL
Part 3 focuses on to . It addresses the persistence of objects into rela- tional databases. It will also help you discover how to query SQL Server databases with LINQ . Advanced LINQ to SQL features are also presented, such as inherit- ance, transactions, stored procedures, and more.
LINQ
XML
Part 4 covers to . It demonstrates how to use LINQ for creating and processing
XML documents. In this part, you’ll see what LINQ to
XML has to offer
compared to the other
XML API s. A comprehensive set of examples covers the
most common LINQ to XML use cases.
Part 5 covers extensibility and shows how the LINQ flavors fit in a complete application. The extensibility chapter demonstrates various ways to enrich the
LINQ toolset. The last chapter analyzes the use of LINQ in our running example and discusses choices you can make when you use LINQ .
The appendix contains a reference of the standard query operators, a key con- stituent of LINQ queries. Resources provides pointers to resources that will help you to learn more about LINQ , such as Microsoft’s official web sites, articles, weblogs or forums.
onstrates how LINQ can be used to query DataSets and DataTables.
It’s up to you to decide whether you want to read the book from start to finish or jump right into one precise chapter. Wherever you are in the book, we tried to make it easy for you to navigate between chapters.
Tools used
The LINQ technology is included in . NET
3.5. It is supported by Visual Studio 2008, C# 3.0, and
VB.NET
9.0. All the content of this book and the code samples it
1
contains are based on Visual Studio 2008 and . NET 3.5 RTM , the final products. You can refer to section 1.4.1 to find a detailed list of software requirements for working with LINQ and this book’s samples.
Source code
This book contains extensive source code examples in C# and
VB.NET . All code 1 examples can be found as a downloadable archive at the book’s web site at Release To Manufacturing. A B O U T T H I S B O O K
http://www.manning.com/ LINQ inAction and at http://LinqInAction.net. Not all the examples are provided in both C# and
VB.NET at the same time in the book, but they’re all available in both languages in the companion source code.
Conventions
When we write “ LINQ ,” we’re referring to the LINQ technology or the complete
LINQ framework. When we write “ LINQ toolset,” we mean the set of tools LINQ
offers: LINQ to Objects, LINQ to
XML , LINQ to SQL , and the others. We’ll explic- LINQ to Objects, LINQ to
XML LINQ to SQL
itly use , or to refer to specific parts of the LINQ toolset.
Typographical conventions special code font
This book uses a whenever certain code terms such as classes, objects, or operator names appear in the main text.
Particular bits of code that we want to draw attention to appear in bold. Fur- thermore, all code results and console output appears in italics. Code annotations accompany many of the listings, highlighting important
B
concepts. In some cases, numbered bullets link to explanations that follow the listing.
Icons like this differentiate between code in C# and
VB.NET : Author Online
Purchase of LINQ in Action includes free access to a private web forum run by Man- ning Publications where you can make comments about the book, ask technical questions, and receive help from the authors and from other users. To access the
are registered, what kind of help is available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaning- ful dialogue between individual readers and between readers and the authors can take place. It is not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions, lest their interest stray! A B O U T T H I S B O O K
The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
About the authors F ABRICE M ARGUERIE
is a software architect and developer with more than 13 years of experience in the software industry. He has diverse experience, ranging from consulting services and training to starting his own business. Fabrice has been awarded the C# MVP title by Microsoft in recognition for his involvement in the . NET community. His activities include speaking at conferences, writing technical articles in English and French, writing a weblog about . NET , and running websites such as sharptoolbox.com and proagora.com. Fabrice is based in Paris, France.
TEVE
ICHERT
S E is an architect and technical lead at Algorithmics, Inc. He also
runs his own consulting company where he specializes in delivering solutions to clients utilizing the latest Microsoft . NET technologies. Steve can be found online at http://iqueryable.com. He is married and has three beautiful children. Steve is based in Philadelphia.
J
IM W OOLEY
has been working with . NET since PDC 2000 and has been actively evangelizing LINQ since its announcement in 2005. He leads the Atlanta
VB Study
Group and serves as INETA Membership Manager for the Georgia region.
About the title
By combining introductions, overviews, and how-to examples, the In Action books are designed to help learning and remembering. According to research in cogni- tive science, the things people remember are things they discover during self- motivated exploration.
Although no one at Manning is a cognitive scientist, we are convinced that for learning to become permanent it must pass through stages of exploration, play, and, interestingly, re-telling of what is being learned. People understand and remember new things, which is to say they master them, only after actively explor- ing them. Humans learn in action. An essential part of an In Action book is that it is example-driven. It encourages the reader to try things out, to play with new code, and explore new ideas.
There is another, more mundane, reason for the title of this book: our readers are busy. They use books to do a job or solve a problem. They need books that allow them to jump in and jump out easily and learn just what they want just when
A B O U T T H I S B O O K
they want it. They need books that aid them in action. The books in this series are designed for such readers.
About the cover illustration LINQ in Action reads “La Champenoise”
The caption for the figure on the cover of or “The Champagne One.” The drawing is of a young woman from the historic province of Champagne in the northeast of France, best known for the produc- tion of the sparkling white wine that bears the region’s name. The illustration is taken from a French travel book, Encyclopedie des Voyages by J. G. St. Saveur, pub- lished in 1796. Travel for pleasure was a relatively new phenomenon at the time and travel guides such as this one were popular, introducing both the tourist as well as the armchair traveler to the inhabitants of other regions of the world, as well as to the and regional costumes and uniforms of French soldiers, civil ser- vants, tradesmen, merchants, and peasants.
The diversity of the drawings in the Encyclopedie des Voyages speaks vividly of the uniqueness and individuality of the world’s towns and provinces just 200 years ago. This was a time when the dress codes of two regions separated by a few dozen miles identified people uniquely as belonging to one or the other. The travel guide brings to life a sense of isolation and distance of that period and of every other historic period except our own hyperkinetic present.
Dress codes have changed since then and the diversity by region, so rich at the time, has faded away. It is now often hard to tell the inhabitant of one continent from another. Perhaps, trying to view it optimistically, we have traded a cultural and visual diversity for a more varied personal life. Or a more varied and interest- ing intellectual and technical life.
We at Manning celebrate the inventiveness, the initiative, and the fun of the computer business with book covers based on the rich diversity of regional life two centuries ago brought back to life by the pictures from this travel guide.
Part 1 Getting started
his part of the book introduces the LINQ technology and the C# and
T
VB language enhancements.
Chapter 1 presents LINQ , its history, the reasons to use it, and quick XML SQL “hello world” examples with objects, , and . Chapter 2 introduces all the new languages features provided by the latest versions of C# and
VB.NET LINQ LINQ
to enable . Chapter 3 covers ’s technical fundamentals and shows how they fit together.
3 Introducing LINQ This chapter covers ■
LINQ’s origins ■ LINQ’s design goals ■ First steps with LINQ to Objects, LINQ to XML, and LINQ to SQL
CHAPTER 1 Introducing LINQ Software is simple. It boils down to two things: code and data. Writing software is
not so simple, and one of the major activities it involves is writing code that deals with data.
To write code, we can choose from a variety of programming languages. The selected language for an application may depend on the business context, on developer preferences, on the development team’s skills, on the operating system, or on company policy.
Whatever language you end up with, at some point you will have to deal with data. This data can be in files on a disk, tables in a database, or
XML documents
coming from the Web, or often you have to deal with a combination of all of these. Ultimately, managing data is a requirement for every software project you’ll work on.
Given that dealing with data is such a common task for developers, we would
NET
expect rich software development platforms like the . Framework to provide an easy way to do it. . NET does provide wide support for working with data. You will see, however, that something had yet to be achieved: deeper language and data integration. This is where LINQ to Objects, LINQ to
XML , and LINQ to SQL fit in.
The technologies we present in this book have been designed as a new way to write code. This book has been written by developers for developers, so don’t be afraid: You won’t have to wait too long before you are able to write your first lines of LINQ code! In this chapter, we will quickly introduce “hello world” pieces of code to give you hints on what you will discover in the rest of the book. The aim is that, by the end of the book, you will be able to tackle real-world projects while
LINQ being convinced that is a joy to work with.
The intent of this first chapter is to give you an overview of LINQ and to help
LINQ
you identify the reasons to use it. We will start by providing an overview of and the LINQ toolset, which includes LINQ to Objects, LINQ to
XML , and LINQ to SQL
. We will then review some background information to clearly understand why we need LINQ and where it comes from. The second half of this chapter will guide
LINQ you while you make your first steps with code.
1.1 What is LINQ?
Suppose you are writing an application using . NET . Chances are high that at some point you’ll need to persist objects to a database, query the database, and load the results back into objects. The problem is that in most cases, at least with relational databases, there is a gap between your programming language and the database. Good attempts have been made to provide object-oriented databases, which
What is LINQ?
would be closer to object-oriented platforms and imperative programming lan-
VB.NET
guages such as C# and . However, after all these years, relational databases are still pervasive, and you still have to struggle with data access and persistence in all of your programs.
The original motivation behind LINQ was to address the conceptual and tech-
NET
nical difficulties encountered when using databases with . programming lan- guages. With LINQ , Microsoft’s intention was to provide a solution for the problem of object-relational mapping, as well as to simplify the interaction between objects and data sources. LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to access data com- ing from in-memory objects ( LINQ to Objects), databases ( LINQ to SQL ),
XML LINQ
XML documents ( to ), a file-system, or any other source.
We will first give you an overview of what LINQ is, before looking at the tools it
LINQ
offers. We will also introduce how extends programming languages.1.1.1 Overview
LINQ could be the missing link—whether this pun is intended is yet to be discov-
ered—between the data world and the world of general-purpose programming languages. LINQ unifies data access, whatever the source of data, and allows mix- ing data from different kind of sources. It allows for query and set operations, sim- ilar to what SQL statements offer for databases. LINQ , though, integrates queries
NET
directly within . languages such as C# and Visual Basic through a set of exten- sions to these languages: LINQ means Language-INtegrated Query.
LINQ SQL
XML
XP
Before , we had to juggle different languages like , , or ath along with various technologies and API s like ADO.NET or System.Xml in every
VB.NET
application written using general-purpose languages such as C# or . It goes
1
without saying that this approach had several drawbacks. LINQ glues several worlds together. It helps us avoid the bumps we would usually find on the road from one world to another: using
XML with objects, objects with relational data,
XML LINQ and relational data with are some of the tasks that will simplify.
One of the key aspects of LINQ is that it was designed to be used against any type of object or data source and to provide a consistent programming model for 1 doing so. The syntax and concepts are the same across all of its uses: Once you
“It was like you had to order your dinner in one language and drinks in another,” said Jason McConnell,
product manager for Visual Studio at Microsoft. “The direct benefit is programmers are more produc-
tive because they have this unified approach to querying and updating data from within their language.”
CHAPTER 1 Introducing LINQ
learn how to use LINQ against an array or a collection, you also know most of the
LINQ
XML concepts needed to take advantage of with a database or an file.
Another important aspect of LINQ is that when you use it, you work in a strongly typed world. The benefits include compile-time checking for your que- ries as well as nice hints from Visual Studio’s IntelliSense feature.
LINQ
will significantly change some aspects of how you handle and manipulate data with your applications and components. You will discover how LINQ is a step toward a more declarative programming model. Maybe you will wonder in the not-so-distant future why you used to write so many lines of code.
LINQ LINQ
There is duality in . You can conceive of as consisting of two com- plementary parts: a set of tools that work with data, and a set of programming lan- guage extensions.
You’ll first see how LINQ is a toolset that can be used to work with objects,
XML LINQ
documents, relational databases, or other kinds of data. You’ll then see how is also an extension to programming languages like C# and
VB.NET .
1.1.2 LINQ as a toolset
LINQ
offers numerous possibilities. It will significantly change some aspects of how you handle and manipulate data with your applications and components. In this
LINQ LINQ providers— LINQ
book, we’ll detail the use of three major flavors of , or to Objects, LINQ to SQL , and LINQ to
XML , respectively—in parts 2, 3, and 4. These LINQ
three providers form a family of tools that can be used separately for partic- ular needs or combined for powerful solutions.
LINQ LINQ SQL LINQ
XML
We will focus on to Objects, to , and to in this book, but LINQ is open to new data sources. The three main LINQ providers discussed
LINQ
in this book are built on top of a common foundation. This foundation con- sists of a set of building blocks including query operators, query expressions, and expres-
sion trees, which allow the LINQ toolset to be extensible.
Other variants of LINQ can be created to provide access to diverse kinds of
LINQ
data sources. Implementations of will be released by software vendors, and you can also create your own implementations, as you’ll see in chapter 12, which
LINQ LINQ
covers ’s extensibility. You can plug a wide array of data sources into , including the file system, Active Directory, WMI, the Windows Event Log, or any
API LINQ
other data source or . This is excellent because you can benefit from ’s features with a lot of the data sources you deal with every day. In fact, Microsoft
LINQ LINQ LINQ SQL
already offers more providers than just to Objects, to , and
LINQ to
XML . Two of them are LINQ to DataSet and LINQ to Entities (to work
What is LINQ?
Figure 1.1 LINQ building blocks, LINQ providers, and data sources that can be queried using LINQwith the new ADO.NET Entity Framework). We will present these tools in the sec- ond and third parts of this book. For now, let’s keep the focus on the big picture.
Figure 1.1 shows how we can represent the LINQ building blocks and toolset in a diagram.The LINQ providers presented in figure 1.1 are not standalone tools. They can be used directly in your programming languages. This is possible because the
LINQ framework comes as a set of language extensions. This is the second aspect of LINQ , which is detailed in the next section.
1.1.3 LINQ as language extensions
LINQ allows you to access information by writing queries against various data
2 2 sources. Rather than being simply syntactic sugar that would allow you to easily
Syntactic sugar is a term coined by Peter J. Landin for additions to the syntax of a computer language
that do not affect its expressiveness but make it “sweeter” for humans to use. Syntactic sugar gives the
programmer an alternative way of coding that is more practical, either by being more succinct or more
like some familiar notation.CHAPTER 1 Introducing LINQ
Figure 1.2 shows a typical language-integrated query that is used to talk to objects,known as
VB
2008), and as such requires dedicated compilers, but it can be ported to other . NET languages. This is already the case for F#, a functional lan- guage for .
NET
from Microsoft Research, and you can expect to see
LINQ
support appear in more . NET languages in the future.
XML , or data tables.
provides a common querying archi- tecture across programming languages. It works with C# 3.0 and
The query in the figure is expressed in C# and not in a new language.
LINQ
is not a new language. It is integrated into C# and
VB.NET . In addition, LINQ can be used to avoid entangling your . NET
programming language with
SQL
, XSL, or
Listing 1.1 Sample code that uses LINQ to query a database and create an XML document
Retrieve customers from database Generate XML data from list of customersVB.NET 9.0 (also
include database queries right into your C# code, LINQ provides the same type of expressive capabilities that
SQL
LINQ
offers, but in the programming language of your choice. This is great because a declarative approach like the one LINQ offers allows you to write code that is shorter and to the point.
Listing 1.1 shows sample C# code you can write with LINQ .
var contacts = from customer in db.Customers where customer.Name.StartsWith("A") && customer.Orders.Count > 0 orderby customer.Name select new { customer.Name, customer.Phone }; var xml = new XElement("contacts", from contact in contacts select new XElement("contact", new XAttribute("name", contact.Name), new XAttribute("phone", contact.Phone) ) );
The listing demonstrates all you need to write in order to extract data from a data- base and create an
XML
document from it. Imagine how you would do the same without LINQ , and you’ll realize how things are easier and more natural with
LINQ
. You will soon see more
queries, but let’s keep focused on the lan- guage aspects for the moment. With the
We’ve just shown you code in C#, but
from
,
where
,
orderby
, and
select
key- words in the listing, it’s obvious that C# has been extended to enable language- integrated queries.
LINQ
Why do we need LINQ?