Găsiți următorul dvs. carte preferat
LINQ Quickly
Descriere
Despre autor
Autori similari
Legat de LINQ Quickly
Categorii relevante
Previzualizare carte
LINQ Quickly - N Satheesh Kumar
Table of Contents
LINQ Quickly
Credits
About the Author
About the Reviewer
Preface
What This Book Covers
Conventions
Reader Feedback
Customer Support
Downloading the Example Code for the Book
Errata
Questions
1. Overview
LINQ Architecture
Integration with SQL
Integration with XML
Support for C# 3.0 Language Features
Anonymous Types
Object Initializers
Collection Initializers
Partial Methods
Implicitly Typed Local Variables
Extensions
Expressions
Lambda Expressions
Query Expressions
Expression Trees
Summary
2. LINQ to Objects
Array of Integers
Collection of Objects
Reading from Strings
Reading from Text Files
Summary
3. LINQ to XML
Features
Class Library
Classes and Hierarchy
XElement Class
XAttribute Class
XDocument Class
Other Classes
LINQ to XML with Other XML Technologies
LINQ with XmlReader
LINQ with XSLT
LINQ with MSXML
Functional Construction
XML Names
Loading and Traversing XML
Loading XML
Traversing XML
Data Manipulation
Inserting or Adding Elements to XML
Inserting or Adding XML Attributes
Deleting XML
Updating XML
Deleting XML Attributes
Updating XML Attributes
Outputting and Streaming XML
Streaming XML
Querying XML
Query Operators
Queries
Ancestors and Descendants
XML Transformation
Dictionaries
Convert Dictionary to XML
Create Dictionary from XML
Writing XML as Text Files and CSV Files
Reading from CSV Files
LINQ to XML Events
XML Literals and Embedded Expressions in Visual Basic
Summary
4. LINQ to SQL
Working with Databases Using DataContext
Entity Classes
Attributes
Database Attribute
Table Attribute
Column Attribute
Association Attribute (Foreign Keys)
Relationships
Function Attribute
Parameter Attribute
Inheritance Mapping Attribute
Creating and Deleting Databases
DataContext Methods
Data Manipulation
LINQ to SQL Queries
Identifying Objects
Queries with Multiple Entities
Remote Queries and Local Queries
Deferred Loading
Immediate Loading
Projections
Constructing XML
Joins
Raw SQL Query
Query Result
Stored Procedures
User-Defined Functions
Class Generator Tool
Transactions
Handling Concurrency Conflicts
Object Relational Designer (O/R Designer)
Summary
5. LINQ over DataSet
Loading Data into DataSets
Querying Datasets
Sequence Operator
Querying Typed DataSets
DataSet Query Operators
CopyToDataTable
LoadDataRow
Intersect
Union
Except
Field
SetField
Projection
Join
SequenceEqual
Skip
Distinct
Summary
6. LINQ to XSD
Un-typed XML
Typed XML
Creating Typed XML using Visual Studio
Object Construction
Load Method
Parse Method
Save Method
Clone Method
Default Values
Customization of XML Objects
Mapping Time Customization
Compile Time Customization
Post Compile Customization
Using LINQ to XSD at Command Line
Summary
7. Standard Query Operators
Restriction Operators
Where
OfType
Projection Operators
Select
SelectMany
Join Operators
Join
GroupJoin
Concatenation Operator
Concat
Ordering Operators
Set Operators
Distinct
Except
Intersect
Union
Grouping Operators
GroupBy
ToLookup
Conversion Operators
AsEnumerable
Cast
OfType
ToArray
ToDictionary
ToList
ToLookup
Equality Operators
SequenceEqual
Generation Operators
Empty
Range
Repeat
Quantifiers
All
Any
Contains
Aggregation Operators
Average
Count
LongCount
Min
Max
Sum
Aggregate
Partitioning Operators
Take
Skip
TakeWhile
SkipWhile
TakeWhile
Element Operators
DefaultIfEmpty
ElementAt
ElementAtOrDefault
First
FirstOrDefault
Last
LastOrDefault
Single
SingleOrDefault
List of Query Operators
Query Operator Equivalent Expressions
Summary
A. Building an ASP.NET Application
B. LINQ with Outlook
Index
LINQ Quickly
N. Satheesh Kumar
LINQ Quickly
Copyright © 2007 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2007
Production Reference: 1161107
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-847192-54-7
www.packtpub.com
Cover Image by Vinayak Chittar (<vinayak.chittar@gmail.com>)
Credits
Author
N Satheesh Kumar
Reviewer
Granville Barnett
Senior Acquisition Editor
Douglas Paterson
Development Editor
Nikhil Bangera
Technical Editor
Sarvesh Shanbhag
Editorial Manager
Dipali Chittar
Project Manager
Abhijeet Deobhakta
Project Coordinator
Patricia Weir
Indexer
Hemangini Bari
Proofreader
Cathy Cumberlidge
Production Coordinators
Aparna Bhagat
Shantanu Zagade
Cover Designer
Aparna Bhagat
About the Author
N Satheesh Kumar has a Bachelor's Degree in Computer Science Engineering and has around eleven years of experience in software development lifecycle, project and program management. He started his career developing software applications using Borland software products in a company based in India, and then moved to the United Arab Emirates where he continued developing custom application software using Borland Delphi, and customizing Great Plain Dynamics (now known as Microsoft Dynamics) for an automobile company. He moved back to India and spent three years in design and developing application software using Microsoft products for a top multi national company, and then spent a couple of years in project management and program management activities. Now he works as a Technical Architect for a top retail company based in the United States. He works with the latest Microsoft technologies and has published many articles on LINQ and other features of .NET.
About the Reviewer
Granville Barnett's interest in programming has spanned many languages; his talents have been applied most notably at Microsoft. Granville has worked with LINQ since the LINQ May 2006 CTP and has since then advised some of the biggest companies in the world on the successful application of LINQ. Granville has a very active interest in data structures and algorithms, and compiler theory, design and implementation.
He would like to thank all at Microsoft, in particular the members of the UK Application Development Consulting team.
As an author, Granville has written several magazine and web articles on LINQ.
He can be reached through his website at http://gbarnett.org.
Preface
Language Integrated Query (LINQ) is a new feature in Visual Studio 2008 that extends its query capabilities using C# and Visual Basic. Visual Studio 2008 comes with LINQ provider assemblies that enable the use of LINQ with data sources, such as in-memory collections, SQL relational databases, ADO.NET Datasets, XML documents, etc. In Visual Studio 2008, Visual C# and Visual Basic are the languages that implement the LINQ language extensions. LINQ language extensions use the new standard query operators, API, which is the query language for any collection that implements IEnumerable
This book introduces the reader to the basic concepts of LINQ, and takes them through using LINQ with an example-driven approach.
What This Book Covers
Chapter 1 looks at the overall features of LINQ, and gives an overview of different operators provided by LINQ to operate on objects, XML, relational databases, etc.
Chapter 2 examines LINQ to Objects, which means that you can use LINQ to query objects in a collection. Using this feature, you can access in-memory data structures using LINQ. You can directly query collections, and filter out required values without using powerful filtering, ordering, and grouping capabilities.
Chapter 3 looks at LINQ to XML. It is a new in-memory XML programming API to work against XML data. There are different ways of creating XML trees in .NET. LINQ to XML is the new method of creating and manipulating XML data through .NET. The properties and methods of LINQ help in navigating and manipulating XML elements and attributes.
Chapter 4, which covers LINQ to SQL, takes care of translating LINQ expressions into equivalent T-SQL, passing it onto the database for execution, and then returning the results back to the calling application. It reduces programming time and comes with two different design-time tools, which are used for converting relational database objects into object definitions. It also has the ability to create databases, and database objects.
Chapter 5 examines LINQ to DataSets. An ADO.NET DataSet provides a disconnected data source environment for applications. It can be used with multiple data sources. A DataSet has the flexibility of handling data locally in cache memory where the application resides. The application can continue working with a DataSet when it is disconnected from the source and is not dependent on the availability of the data source. The DataSet maintains information about the changes made to data so that updates can be tracked and sent back to the database as soon as the data source is available or reconnected.
Chapter 6 covers LINQ to XSD. It enhances XML programming by adding the feature of typed views on un-typed XML trees. LINQ to XSD gives a better programming environment by providing the object models generated from XML schemas. This is called typed XML programming.
Chapter 7 looks at standard query operators provided by LINQ, and how you can use some of them against different data sources.
Appendix A takes you through building a simple ASP.NET application using LINQ.
Appendix B tells you how to access Outlook objects using LINQ.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
There are three styles for code. Code words in text are shown as follows: LINQ queries work on sources which are IEnumerable<>. The new ADO.NET provides a feature for getting the rows enumerated by applying AsEnumerable() on DataTables.
A block of code will be set as follows:
public class Icecream
{
public string Name { get; set; }
public double Price { get; set; }
}
New terms and important words are introduced in a bold-type font.
Words that you see on the screen, in menus or dialog boxes, for example, appear in our text like this: You can see DataTables listed in the DataSet Visualizer.
Reader Feedback
Feedback from our readers is always welcome. Let us know what you think about this book, what you liked or disliked. Reader feedback is important for us to develop titles that you get the most out of.
To send us general feedback, simply drop an email to <feedback@packtpub.com>, making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email www.packtpub.com/authors.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer Support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the Example Code for the Book
Visit http://www.packtpub.com/support, and select this book from the list of titles to download any example code or extra resources for this book. The files available for download will then be displayed.
The downloadable files contain instructions on how to use them.
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in text or code—we would be grateful if you would report this to us. By doing this you can save other readers from frustration, and help to improve subsequent versions of this book. If you find any errata, report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the Submit Errata link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata are added to the list of existing errata. The existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with some aspect of the book, and we will do our best to address
Chapter 1. Overview
When we say Language Integrated Query, we might think that it is already integrated into the programming language, just as we write SQL queries in our application. So what is the difference or additional features that we are going to get in LINQ? How is LINQ going to make our programming life easier? Also, I am sure that we all want to know how the new feature, LINQ, is making use of the other new features of C# 3.0. We'll see many of those in this book.
LINQ Architecture
Language Integrated Query is a new feature in Visual Studio 2008 that extends the query capabilities, using C# and Visual Basic. Visual Studio 2008 comes with LINQ provider assemblies that enable the use of Language Integrated Queries with different data sources such as in-memory collections, SQL relational database, ADO.NET Datasets, XML documents and other data sources.
In Visual Studio 2008, Visual C# and Visual Basic are the languages that implement the LINQ language extensions. The LINQ language extensions use the new Standard Query Operators API, which is the query language for any collection that implements IEnumerable
The following figure shows the architecture of LINQ, which can query different data sources using different programming languages:
Integration with SQL
LINQ to SQL supports LINQ queries against a relational database for data retrieval and manipulation. Currently in software development, we use Relational data for most of the applications, and we depend on database queries and objects, in some way or the other. The applications use APIs to process or get details from the database by passing queries as strings, or calling database objects by passing parameters. So what is the purpose of LINQ here? Presently scenario, we see a lot of applications, especially multi-tier applications, having a separate data access layer and a business logic layer. If we take the business logic layer, we must have lots of entities or objects to hold the information. These objects represent the database table rows in the form of objects. We use object references similar to primary keys in the database to identify a set of information.
To get data from a relational database to an application, the programmer ends up creating two different types of objects, but in different formats. The other disadvantage is that the programmer has to