linq intro

32
Language Language Integrated Query Integrated Query (LINQ) (LINQ) Nguyen Minh Dao [email protected]

Upload: binh-trong-an

Post on 26-Aug-2014

2.536 views

Category:

Education


1 download

DESCRIPTION

Bài giảng về LINQ

TRANSCRIPT

Page 1: Linq intro

Language Integrated Language Integrated Query (LINQ)Query (LINQ)

Nguyen Minh [email protected]

Page 2: Linq intro

IntroductionIntroduction

• We use many different types of query• SQL, XQuery/XPath, DataView row

filters, etc.• Maybe we could enhance productivity

by...• Deciding on one query expression

syntax• Enabling compilers to check queries &

results• Allow extensibility to target all kinds of

data

Page 3: Linq intro

AgendaAgenda

• C#3 and VB9 Language Enhancements• Building to LINQ to Objects

• LINQ to XML• LINQ to SQL• LINQ to DataSets

Page 4: Linq intro

20062006 20072007 20082008

.NET Framework - VS Roadmap

“Rosario”

• VS Extensions for WFVS Extensions for WF• VS Extensions for WCF/WPF CTPVS Extensions for WCF/WPF CTP

ASP.NET AJAX ASP.NET AJAX 1.01.0

SQL Server 2008 SQL Server 2008 ADO.NET Entity ADO.NET Entity

FrameworkFramework

•VS 2008 Beta 2VS 2008 Beta 2•.NET Framework 3.5 Beta 2.NET Framework 3.5 Beta 2

3.03.0 RTMRTM

3.5 RTM3.5 RTM

Page 5: Linq intro

What is the .NET Framework 3.5?

.NET Framework 2.0 .NET Framework 2.0 + SP1+ SP1

Windows Windows PresentatioPresentatio

n n FoundationFoundation

Windows Windows CommunicatiCommunicati

on on FoundationFoundation

Windows Windows Workflow Workflow

Foundation Foundation Windows Windows

CardSpaceCardSpace

.NET Framework 3.0 + SP1

.NET Framework 3.5

LINQLINQ ASP.NET ASP.NET 3.53.5

CLR Add-in CLR Add-in FrameworkFramework

Additional Additional EnhancemenEnhancemen

tsts

Page 6: Linq intro

Multi-targeting in Visual Studio Multi-targeting in Visual Studio 20082008

Page 7: Linq intro

VB9

Compiler FeaturesCompiler FeaturesMost are LINQ enablers

XML LiteralsRelaxed

Delegates

C# 3.0

Extension Methods

Object Initialisers

Anonymous Types

Local Type Inference

Lambda expressions

Collection Initializers

Partial Methods

Automatic Properties

If Ternary Operator

Nullable Syntax

Lambda statements

Page 8: Linq intro

Language InnovationsLanguage Innovationsvar contacts = from c in customers where c.City == "Hove" select new { c.Name, c.Phone };

var contacts = customers .Where(c => c.City == "Hove") .Select(c => new { c.Name, c.Phone });

Extension methods

Lambda expressions

Query expressions

Object initializersAnonymous

types

Local variable type

inference

Page 9: Linq intro

string name = “Bart”;string reversed = MyExtensions.Reverse(name);

Extension methodsExtension methods• Add methods to existing types “virtually”

• Static method with first “this” parameter• Scoping using namespaces

static class MyExtensions { public static string Reverse(string s) { char[] c = s.ToCharArray(); Array.Reverse(c); return new string(c); }}

string name = “Bart”;string reversed = name.Reverse();

static class MyExtensions { public static string Reverse(this string s) { char[] c = s.ToCharArray(); Array.Reverse(c); return new string(c); }}

Promoted first parameter

Page 10: Linq intro

Automatic propertiesAutomatic properties• Tired of writing properties?

• Compiler can generate the get/set plumbing

class Customer { private string _name; public string Name { get { return _name; }; set { _name = value; }; }}

class Customer { public string Name { get; set; }}

Setter required; can be private or internal

Page 11: Linq intro

Object initializersObject initializers• Ever found the constructor of your taste?

• Insufficient overloads, so pick one• Call various property setters

class Customer { public string Name { get; set; } public int Age { get; set; }}

Customer c = new Customer();c.Name = “Bart”;c.Age = 24;

var c = new Customer(){ Name = “Bart”, Age = 24};

Can be combined with any constructor

call

Page 12: Linq intro

Collection initializersCollection initializers• Arrays easier to initialize than collections?!

int[] ints = new int[] { 1, 2, 3 };List<int> lst = new List<int>();lst.Add(1);lst.Add(2);lst.Add(3);

int[] ints = new int[] { 1, 2, 3 };var lst = new List<int>() { 1, 2, 3 };

Works for any ICollection class by calling its Add

method

Page 13: Linq intro

Anonymous typesAnonymous types• Let the compiler cook up a type

• Can’t be returned from a method• Local variable type inference becomes a must• Used in LINQ query projections

var person = new { Name = “Bart”, Age = 24 };

var customer = new { Id = id, person.Name };

Page 14: Linq intro

Lambda expressionsLambda expressions• Functional-style anonymous methods

delegate R BinOp<A,B,R>(A a, B b);

int Calc(BinOp<int, int, int> f, int a, int b){ return f(a, b)}

int result = Calc( delegate (int a, int b) { return a + b; }, 1, 2);

var result = Calc((a, b) => a + b, 1, 2);

Parameter types inferred based on the target

delegate

Page 15: Linq intro

DemoDemo Anonymous types, Anonymous types,

automatic properties, automatic properties, collection initializers, collection initializers,

extension methodsextension methods

Page 16: Linq intro

First, A Taste of LINQFirst, A Taste of LINQusing System;using System.Query;using System.Collections.Generic; class app { static void Main() {

string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George",

"Harris", "David" };  var expr = from s in names where s.Length == 5 orderby s select s.ToUpper();  foreach (string item in expr) Console.WriteLine(item); }}

BURKEDAVIDFRANK

Page 17: Linq intro

Query ExpressionsQuery Expressions• Introduce SQL-Like Syntax to Language• Compiled to Traditional C# (via Extension Methods)

from itemName in srcExprjoin itemName in srcExpr on keyExpr equals keyExpr

(into itemName)?let itemName = selExprwhere predExprorderby (keyExpr (ascending | descending)?)*select selExprgroup selExpr by keyExpr into itemName query-body

Page 18: Linq intro

LINQLINQ Architecture Architecture

LINQ-enabled data sourcesLINQ-enabled data sources

LINQ LINQ To ObjectsTo Objects

LINQ LINQ To XMLTo XML

LINQ-enabled ADO.NETLINQ-enabled ADO.NET

Visual BasicVisual Basic OthersOthers

LINQ LINQ To EntitiesTo Entities

LINQ LINQ To SQLTo SQL

LINQ LINQ To DatasetsTo Datasets

.Net Language Integrated Query (LINQ).Net Language Integrated Query (LINQ)

Visual C#Visual C#

ObjectsObjects DatabasesDatabases

Page 19: Linq intro

LINQ LINQ ArchitectureArchitecture

LINQ-enabled data sourcesLINQ-enabled data sources

LINQ LINQ To ObjectsTo Objects

LINQ LINQ To XMLTo XML

LINQ-enabled ADO.NETLINQ-enabled ADO.NET

Visual BasicVisual Basic OthersOthers

LINQ LINQ To EntitiesTo Entities

LINQ LINQ To SQLTo SQL

LINQ LINQ To DatasetsTo Datasets

.Net Language Integrated Query (LINQ).Net Language Integrated Query (LINQ)

Visual C#Visual C#

ObjectsObjects DatabasesDatabases

Page 20: Linq intro

using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor",

"Frank", "Everett", "Albert", "George",

"Harris", "David" };  Func<string, bool> filter = s => s.Length == 5; Func<string, string> extract = s => s; Func<string, string> project = s = s.ToUpper();  IEnumerable<string> expr = names

.Where(filter)

.OrderBy(extract) .Select(project);  foreach (string item in expr) Console.WriteLine(item); }}

BURKEDAVIDFRANK

using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Allen", "Arthur",

"Bennett" };  IEnumerable<string> ayes = names

.Where(s => s[0] == 'A');  foreach (string item in ayes)

Console.WriteLine(item);  names[0] = "Bob";  foreach (string item in ayes)

Console.WriteLine(item); }}

Arthur

LINQ to ObjectsLINQ to Objects• Native query

syntax in C# and VB• IntelliSense• Autocompletion

• Query Operators can be used against any .NET collection (IEnumerable<T>)• Select, Where,

GroupBy, Join, etc.• Deferred Query

Evaluation• Lambda

Expressions

using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Allen", "Arthur",

"Bennett" };  IEnumerable<string> ayes = names

.Where(s => s[0] == 'A');  foreach (string item in ayes)

Console.WriteLine(item);  names[0] = "Bob";  foreach (string item in ayes)

Console.WriteLine(item); }}

AllenArthur

using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor",

"Frank", "Everett", "Albert", "George",

"Harris", "David" };  IEnumerable<string> expr =

from s in names where s.Length == 5 orderby s select s.ToUpper();  foreach (string item in expr) Console.WriteLine(item); }}

BURKEDAVIDFRANK

Page 21: Linq intro

LINQLINQ Architecture Architecture

LINQ-enabled data sourcesLINQ-enabled data sources

LINQ LINQ To ObjectsTo Objects

LINQ LINQ To XMLTo XML

LINQ-enabled ADO.NETLINQ-enabled ADO.NET

Visual BasicVisual Basic OthersOthers

LINQ LINQ To EntitiesTo Entities

LINQ LINQ To SQLTo SQL

LINQ LINQ To DatasetsTo Datasets

.Net Language Integrated Query (LINQ).Net Language Integrated Query (LINQ)

Visual C#Visual C#

ObjectsObjects DatabasesDatabases

Page 22: Linq intro

LINQ to SQL OverviewLINQ to SQL Overview

Page 23: Linq intro

LINQ to SQL ArchitectureLINQ to SQL Architecture

ApplicationApplication

LINQ to SQLLINQ to SQL

from c in db.Customerswhere c.City == "London"select c.CompanyName

EnumeratEnumeratee

SELECT CompanyNameFROM CustomerWHERE City = 'London'

SQL QuerySQL Queryor SProcor SProc

RowsRows

ObjectsObjects

db.Customers.Add(c1);c2.City = “Seattle";db.Customers.Remove(c3);

SubmitChanges()SubmitChanges()

INSERT INTO Customer …UPDATE Customer …DELETE FROM Customer …

DML DML or SProcsor SProcs

Page 24: Linq intro

LINQ to SQLLINQ to SQL

• DataContext is the central class• Use code-gen for ORM• SQL is only submitted when needed• Parent-child relationships are

respected• Control of deferred loading

• Can insert/update/delete• Transactionally, with concurrency

checks

Page 25: Linq intro

LINQ to DataSetLINQ to DataSet

• Query expressions over in-memory data

• Works with untyped or typed DataSets

• If query returns some kind of DataRow: -• Can yield results as a DataView• ...and therefore databind to those

results

Page 26: Linq intro

DemoDemo LINQ to ObjectsLINQ to Objects

LINQ to SQLLINQ to SQL

Page 27: Linq intro

LINQLINQ Architecture Architecture

LINQ-enabled data sourcesLINQ-enabled data sources

LINQ LINQ To ObjectsTo Objects

LINQ LINQ To XMLTo XML

LINQ-enabled ADO.NETLINQ-enabled ADO.NET

Visual BasicVisual Basic OthersOthers

LINQ LINQ To EntitiesTo Entities

LINQ LINQ To SQLTo SQL

LINQ LINQ To DatasetsTo Datasets

.Net Language Integrated Query (LINQ).Net Language Integrated Query (LINQ)

Visual C#Visual C#

ObjectsObjects DatabasesDatabases

Page 28: Linq intro

LINQ to XMLLINQ to XML

Creating XMLConstructors lend themselves to nestingCan use LINQ (over anything) to build XML

QueryingUse normal axes from XML infosetGet full power of query expressions over XMLSelect, where, group by, etc.

Xml Namespaces

Page 29: Linq intro

DemoDemo LINQ to XMLLINQ to XML

Page 30: Linq intro

That’s LINQThat’s LINQ

A combination of new language features, and new fx3.5 classes (with extension methods)A common query expression syntaxFreedom to implement across different kinds of dataIt’s TYPED...

The compiler can check your queriesThe compiler can check your results

Page 31: Linq intro

MSDN in the UKMSDN in the UK

Visit http://msdn.co.uk NewsletterEventsNugget VideosBlogs

Page 32: Linq intro

THANK YOUTHANK YOU