linq 090701233237 phpapp01

21
The LINQ Project The LINQ Project Standard Standard Query Query Operators Operators Objects Objects DLinq DLinq (ADO.NET) (ADO.NET) XLinq XLinq (System.Xml) (System.Xml) <book> <title/> <author/> <year/> <price/> </book> XML XML .NET Language Integrated Query .NET Language Integrated Query C# C# VB VB Others… Others… SQL SQL WinFS WinFS

Upload: google

Post on 10-May-2015

362 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Linq 090701233237 Phpapp01

The LINQ ProjectThe LINQ Project

StandardStandardQueryQuery

OperatorsOperators

ObjectsObjects

DLinqDLinq(ADO.NET)(ADO.NET)

XLinqXLinq(System.Xml)(System.Xml)

<book> <title/> <author/> <year/> <price/></book>

XMLXML

.NET Language Integrated Query.NET Language Integrated Query

C#C# VBVB Others…Others…

SQLSQL WinFWinFSS

Page 2: Linq 090701233237 Phpapp01

2

Language Integrated QueryLanguage Integrated Query

Page 3: Linq 090701233237 Phpapp01

3

How does it work?How does it work?

Standard query operatorsStandard query operatorsQuery expressionsQuery expressionsExtension methodsExtension methodsLambda expressionsLambda expressionsExpression treesExpression treesLocal variable type inferenceLocal variable type inference

Page 4: Linq 090701233237 Phpapp01

4

C# 3.0 Language C# 3.0 Language InnovationsInnovations

var contacts =var contacts = from c in customersfrom c in customers where c.State == "WA"where c.State == "WA" select new { c.Name, c.Phone };select new { c.Name, c.Phone };

var contacts =var contacts = customerscustomers .Where(c => c.State == "WA").Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone });.Select(c => new { c.Name, c.Phone });

Extension Extension methodsmethods

Lambda Lambda expressionsexpressions

Query Query expressionsexpressions

Object Object initializersinitializers

Anonymous Anonymous typestypes

Local Local variable type variable type

inferenceinference

Page 5: Linq 090701233237 Phpapp01

5

Lambda Expressions and Lambda Expressions and Extension MethodsExtension Methods

Page 6: Linq 090701233237 Phpapp01

6

Object InitializersObject Initializers

public class Rectanglepublic class Rectangle{{ private Point p1 = new Point();private Point p1 = new Point(); private Point p2 = new Point();private Point p2 = new Point();

public Point P1 { get { return p1; } }public Point P1 { get { return p1; } } public Point P2 { get { return p2; } }public Point P2 { get { return p2; } }}}

Rectangle r = new Rectangle {Rectangle r = new Rectangle { P1 = { X = 0, Y = 1 },P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 }P2 = { X = 2, Y = 3 }};};

Rectangle r = new Rectangle r = new Rectangle();Rectangle();r.P1.X = 0;r.P1.X = 0;r.P1.Y = 1;r.P1.Y = 1;r.P2.X = 2;r.P2.X = 2;r.P2.Y = 3;r.P2.Y = 3;

Embedded Embedded objectsobjects

No “new No “new Point”Point”

Read-only Read-only propertiesproperties

Page 7: Linq 090701233237 Phpapp01

7

Local Variable Type Local Variable Type InferenceInference

int i = 5;int i = 5;string s = "Hello";string s = "Hello";double d = 1.0;double d = 1.0;int[] numbers = new int[] {1, 2, 3};int[] numbers = new int[] {1, 2, 3};Dictionary<int,Order> orders = new Dictionary<int,Order> orders = new Dictionary<int,Order>();Dictionary<int,Order>();

var i = 5;var i = 5;var s = "Hello";var s = "Hello";var d = 1.0;var d = 1.0;var numbers = new int[] {1, 2, 3};var numbers = new int[] {1, 2, 3};var orders = new Dictionary<int,Order>();var orders = new Dictionary<int,Order>();

““var” means var” means same type as same type as

initializerinitializer

Page 8: Linq 090701233237 Phpapp01

8

Anonymous TypesAnonymous Typespublic class Customerpublic class Customer{{ public string Name;public string Name; public Address Address;public Address Address; public string Phone;public string Phone; public List<Order> Orders;public List<Order> Orders; … …}}

public class Contactpublic class Contact{{ public string Name;public string Name; public string Phone;public string Phone;}}

Customer c = GetCustomer(…);Customer c = GetCustomer(…);Contact x = Contact x = new Contact { Name = c.Name, Phone = new Contact { Name = c.Name, Phone = c.Phone }c.Phone };;

Customer c = GetCustomer(…);Customer c = GetCustomer(…);var x = var x = new { c.Name, c.Phone }new { c.Name, c.Phone };;

Customer c = GetCustomer(…);Customer c = GetCustomer(…);var x = var x = new { Name = c.Name, Phone = c.Phone }new { Name = c.Name, Phone = c.Phone };;

class ???class ???{{ public string public string Name;Name; public string public string Phone;Phone;}}

Projection style Projection style initializerinitializer

Page 9: Linq 090701233237 Phpapp01

9

Query ExpressionsQuery Expressions

Language integrated query syntaxLanguage integrated query syntax

fromfrom idid inin sourcesource{ { fromfrom idid inin sourcesource | | wherewhere conditioncondition } }[ [ orderbyorderby orderingordering, , orderingordering, … ], … ]selectselect exprexpr | | groupgroup exprexpr byby keykey[ [ intointo idid queryquery ] ]

Starts with Starts with fromfrom Zero or more Zero or more

fromfrom or or wherewhere

Optional Optional orderbyorderby

Ends with Ends with selectselect or or groupgroup bybyOptional Optional intointo

continuationcontinuation

Page 10: Linq 090701233237 Phpapp01

10

from c in customersfrom c in customerswhere c.State == "WA"where c.State == "WA"select new { c.Name, c.Phone };select new { c.Name, c.Phone };

customerscustomers.Where(c => c.State == "WA").Where(c => c.State == "WA").Select(c => new { c.Name, c.Phone });.Select(c => new { c.Name, c.Phone });

Query ExpressionsQuery Expressions

Queries translate to method Queries translate to method invocationsinvocations

Where, Select, SelectMany, OrderBy, Where, Select, SelectMany, OrderBy, GroupByGroupBy

Page 11: Linq 090701233237 Phpapp01

11

C# 3.0 Language C# 3.0 Language InnovationsInnovations

Lambda expressionsLambda expressions

Extension methodsExtension methods

Local variable type inferenceLocal variable type inference

Object initializersObject initializers

Anonymous typesAnonymous types

Query expressionsQuery expressions

Expression treesExpression trees

var x = 5;var x = 5;

static void Dump(this static void Dump(this object o);object o);

c => c => c.Namec.Name

new Point { x = 1, y new Point { x = 1, y = 2 }= 2 }

new { c.Name, new { c.Name, c.Phone }c.Phone }

from … where … from … where … selectselect

Expression<TExpression<T>>

Page 12: Linq 090701233237 Phpapp01

12

Standard Query OperatorsStandard Query OperatorsRestrictionRestriction WhereWhere

ProjectionProjection Select, SelectManySelect, SelectMany

OrderingOrdering OrderBy, ThenByOrderBy, ThenBy

GroupingGrouping GroupByGroupBy

QuantifiersQuantifiers Any, AllAny, All

PartitioningPartitioning Take, Skip, TakeWhile, SkipWhileTake, Skip, TakeWhile, SkipWhile

SetsSets Distinct, Union, Intersect, ExceptDistinct, Union, Intersect, Except

ElementsElements First, FirstOrDefault, ElementAtFirst, FirstOrDefault, ElementAt

AggregationAggregation Count, Sum, Min, Max, AverageCount, Sum, Min, Max, Average

ConversionConversion ToArray, ToList, ToDictionaryToArray, ToList, ToDictionary

CastingCasting OfType<T>OfType<T>

Page 13: Linq 090701233237 Phpapp01

13

Deferred Query ExecutionDeferred Query ExecutionCustomer[] custs = SampleData.GetCustomers();Customer[] custs = SampleData.GetCustomers();

custscusts

PhonePhoneNameNameIDID

var query = from c in custs where c.City == "London" select var query = from c in custs where c.City == "London" select c.Name;c.Name;

var query = custs.Where(c => c.City == "London").Select(c var query = custs.Where(c => c.City == "London").Select(c => c.Name);=> c.Name);

SelectSelect

c => c => c.Namec.Name

string[] names = query.ToArray();string[] names = query.ToArray();

namesnames

c => c.City == c => c.City == "London""London"

WhereWhere

Page 14: Linq 090701233237 Phpapp01

14

DLinq For Relational DataDLinq For Relational Data

SqlConnection c = new SqlConnection(…);SqlConnection c = new SqlConnection(…);c.Open();c.Open();SqlCommand cmd = new SqlCommand(SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone@"SELECT c.Name, c.Phone FROM Customers cFROM Customers c WHERE c.City = @p0");WHERE c.City = @p0");cmd.Parameters.AddWithValue("@p0", cmd.Parameters.AddWithValue("@p0", "London“);"London“);DataReader dr = c.Execute(cmd);DataReader dr = c.Execute(cmd);while (dr.Read()) {while (dr.Read()) { string name = dr.GetString(0);string name = dr.GetString(0); string phone = dr.GetString(1);string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2);DateTime date = dr.GetDateTime(2);}}dr.Close();dr.Close();

Accessing data todayAccessing data todayQueries in Queries in

quotesquotes

Loosely Loosely bound bound

argumentsarguments

Loosely Loosely typed result typed result

setssets

No compile No compile time checkstime checks

Page 15: Linq 090701233237 Phpapp01

15

public class Customer { … }public class Customer { … }

public class Northwind: DataContextpublic class Northwind: DataContext{{ public Table<Customer> Customers;public Table<Customer> Customers; … …}}

Northwind db = new Northwind(…);Northwind db = new Northwind(…);var contacts =var contacts = from c in db.Customersfrom c in db.Customers where c.City == "London"where c.City == "London" select new { c.Name, c.Phone };select new { c.Name, c.Phone };

DLinq For Relational DataDLinq For Relational Data

Accessing data with DLinqAccessing data with DLinqClasses Classes

describe datadescribe data

Strongly Strongly typed typed

connectionconnection

Integrated Integrated query syntaxquery syntax

Strongly Strongly typed resultstyped results

Tables are Tables are like like

collectionscollections

Page 16: Linq 090701233237 Phpapp01

16

DLinq For Relational DataDLinq For Relational Data

Language integrated data accessLanguage integrated data accessMaps tables and rows to classes and Maps tables and rows to classes and objectsobjects

Builds on ADO.NET and .NET Builds on ADO.NET and .NET TransactionsTransactions

MappingMappingEncoded in attributesEncoded in attributes

Relationships map to propertiesRelationships map to properties

PersistencePersistenceAutomatic change trackingAutomatic change tracking

Updates through SQL or stored Updates through SQL or stored proceduresprocedures

Page 17: Linq 090701233237 Phpapp01

17

XLinq For XML DataXLinq For XML Data

XmlDocument doc = new XmlDocument();XmlDocument doc = new XmlDocument();XmlElement contacts = doc.CreateElement("contacts");XmlElement contacts = doc.CreateElement("contacts");foreach (Customer c in customers)foreach (Customer c in customers) if (c.Country == "USA") {if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact");XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name");XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName;name.InnerText = c.CompanyName; e.AppendChild(name);e.AppendChild(name); XmlElement phone = doc.CreateElement("phone");XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone;phone.InnerText = c.Phone; e.AppendChild(phone);e.AppendChild(phone); contacts.AppendChild(e);contacts.AppendChild(e); }}doc.AppendChild(contacts);doc.AppendChild(contacts);

Programming XML todayProgramming XML today

<contacts><contacts> <contact><contact> <name>Great Lakes <name>Great Lakes Food</name>Food</name> <phone>(503) <phone>(503) 555-7123</phone>555-7123</phone> </contact></contact> … …</contacts></contacts>

Imperative Imperative modelmodel

Document Document centriccentric

No integrated No integrated queriesqueries

Memory Memory intensiveintensive

Page 18: Linq 090701233237 Phpapp01

18

XLinq For XML DataXLinq For XML Data

XElement contacts = new XElement("contacts",XElement contacts = new XElement("contacts", from c in customersfrom c in customers where c.Country == "USA"where c.Country == "USA" select new XElement("contact",select new XElement("contact", new XElement("name", c.CompanyName),new XElement("name", c.CompanyName), new XElement("phone", c.Phone)new XElement("phone", c.Phone) ))););

Programming XML with XLinqProgramming XML with XLinqDeclarative Declarative

modelmodel

ElementElementcentriccentric

Integrated Integrated queriesqueries

Smaller and Smaller and fasterfaster

Page 19: Linq 090701233237 Phpapp01

19

XLinq For XML DataXLinq For XML Data

Language integrated query for XMLLanguage integrated query for XMLExpressive power of XPath / XQueryExpressive power of XPath / XQuery

But with C# or VB as programming But with C# or VB as programming languagelanguage

Leverages experience with DOMLeverages experience with DOMElement centric, not document centricElement centric, not document centric

Functional constructionFunctional construction

Text nodes are just stringsText nodes are just strings

Simplified XML namespace supportSimplified XML namespace support

Faster and smallerFaster and smaller

Page 20: Linq 090701233237 Phpapp01

20

The LINQ ProjectThe LINQ Project

Language Integrated Query for .NETLanguage Integrated Query for .NETNative query syntax in C# 3.0 and VB Native query syntax in C# 3.0 and VB 9.09.0

Standard Query OperatorsStandard Query OperatorsSQL-like queries for any .NET collectionSQL-like queries for any .NET collection

DLinqDLinqQuery enabled data access frameworkQuery enabled data access framework

XLinqXLinqQuery enabled, smaller, faster XML DOMQuery enabled, smaller, faster XML DOM

Page 21: Linq 090701233237 Phpapp01

21

Benefits Of LINQBenefits Of LINQ

Unified querying of objects, Unified querying of objects,

relational, XMLrelational, XML

Type checking and IntelliSense for Type checking and IntelliSense for

queries queries

SQL and XQuery-like power in C# SQL and XQuery-like power in C#

and VBand VB

Extensibility model for languages / Extensibility model for languages /

APIsAPIs