1. Trang chủ
  2. » Công Nghệ Thông Tin

Language Integrated Query potx

93 1,7K 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Language Integrated Query Potx
Trường học Ho Chi Minh University of Industry
Chuyên ngành Computer Science
Thể loại Lecture Notes
Thành phố Ho Chi Minh City
Định dạng
Số trang 93
Dung lượng 4,1 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

HO CHI MINH UNIVERSITY OF INDUSTRYprivate void btnNoi_Click object sender, EventArgs e... HO CHI MINH UNIVERSITY OF INDUSTRY public static int SumFrom1toN this int n {… } public static

Trang 1

HO CHI MINH UNIVERSITY OF INDUSTRY

LINQ

Language Integrated

Query

Trang 2

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 3

HO CHI MINH UNIVERSITY OF INDUSTRY

2 New features in language:

Trang 4

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 5

HO CHI MINH UNIVERSITY OF INDUSTRY

2.1 Implicitly Typed Variables

– Declare variables without specifying their type

– Strongly type, not variant, not object

– Visual Studio will determine type

• Predict what the compiler will choose

• Intelligence support

– Type inference -> most general

• “3/10/2010” -> string, not date

Trang 6

HO CHI MINH UNIVERSITY OF INDUSTRY

2.1 Implicitly Typed Variables

{ var x = 113;

var y = "1/1/2012" ;

var z = 1.7;

var k = new DateTime (2012, 1, 1);

string msg = "x type=" +x.GetType() + "\n" +

"y type = " +y.GetType() + "\n" +

"z type =" +z.GetType() + "\n" +

"k type = " + k.GetType();

MessageBox Show(msg);

}

Trang 7

HO CHI MINH UNIVERSITY OF INDUSTRY

2.1 Implicitly Typed Variables

– Always declare the type if we know

– Implicitly Typed Variables are suited for LINQ and anonymous type

Trang 8

HO CHI MINH UNIVERSITY OF INDUSTRY

2.2 Object Initializers

 Constructor

 Allow to assign values to object properties (fields) when create object

 We do not have to explicitly invoke a constructor

 Useful in any context

– Especially useful in LINQ expressions

Trang 9

HO CHI MINH UNIVERSITY OF INDUSTRY

public int a2 { set ; get ;}

public int b2 { get ; set ; }

Trang 10

HO CHI MINH UNIVERSITY OF INDUSTRY

2.3 Anonymous Types

– Set property values to object without writing class definition

– The resulting class has no usable name

– Class name is generated by compiler, inherits from Object

– The result: an anonymous type that is not available at source code level

Trang 11

HO CHI MINH UNIVERSITY OF INDUSTRY

2.3 Anonymous Types

– Need a temporary object to hold related data

– Don’t need method

– If we need a different set of properties for each declaration

– If we need to change the order of properties for each declaration

Trang 12

HO CHI MINH UNIVERSITY OF INDUSTRY

2.3 Anonymous Types

– Need to define methods

– Need to define another variable

– Need to shared data across methods

private void btn4_Click( object sender, EventArgs e)

{

var teo = new { ID=1234,Name= "Tèo Hả Tèo" };

MessageBox Show(teo.ID + "-" +teo.Name);

}

Trang 13

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4 Extension Methods

 Special kind of Static method

 Allow the addition of methods to an existing class

– Without creating a new derived type

– Without re-compiling or modifying the original type

 Called The Same way regular methods are called

 Define in static class

Trang 14

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 15

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4 Extension Methods

MessageBox Show(n.SumFrom1toN()+ "" );

Trang 16

HO CHI MINH UNIVERSITY OF INDUSTRY

namespace StudyLinQ

{

public static class MyExtensionMethod

{

public static int SumFrom1toN( this int n){…}

Trang 17

HO CHI MINH UNIVERSITY OF INDUSTRY

private void btnNoi_Click

( object sender, EventArgs e)

Trang 18

HO CHI MINH UNIVERSITY OF INDUSTRY

public static int SumFrom1toN( this int n) {… }

public static string NoiChuoi( this string s1, string s2){…}

public static void ChangeColorToRed( this Button btn)

Trang 19

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4 Extension Methods

btnColor.ChangeColorToRed();

Trang 20

HO CHI MINH UNIVERSITY OF INDUSTRY

public delegate int ChangeInt ( int x);

public int Tang2( int x){ return x + 2;}

public int Giam2( int x) { return x - 2;}

Trang 21

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a Delegate

private void btndlg_Click

( object sender, EventArgs e)

Trang 22

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a delegate: why?

Trang 23

HO CHI MINH UNIVERSITY OF INDUSTRY

private void btnEven_Click( object sender, EventArgs e)

Trang 24

HO CHI MINH UNIVERSITY OF INDUSTRY

private bool isPrime( int x)

Trang 25

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a delegate: why?

public static class MyExtensionMethod

{

public delegate bool HandleFunction ( int x);

public static void SelectItemInListBox(this ListBox lst,

Trang 26

HO CHI MINH UNIVERSITY OF INDUSTRY

private bool isEven( int x)

Trang 27

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a delegate: why?

private void btnEven_Click( object sender, EventArgs e)

Trang 28

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a delegate: with anonymous

private void button7_Click

( object sender, EventArgs e)

Trang 29

HO CHI MINH UNIVERSITY OF INDUSTRY

2.4.a delegate: with anonymous

Exercise:

Trang 30

HO CHI MINH UNIVERSITY OF INDUSTRY

2.5 Lambda Expressions

– A function without a name

– Perform action , return a single value

– Can be used wherever a delegate type is valid

– Allow a function’s caller to define the action

– Not just pass parameters

– Lambda expressions provide a clearer syntax for anonymous delegates

Trang 31

HO CHI MINH UNIVERSITY OF INDUSTRY

2.5 Lambda Expressions: delegate

Syntax

– parameters => expression

– a functional superset of anonymous methods

– Lambda expressions can "infer" parameter types, even if you omit them

– Lambda expressions can use both statement blocks and expressions

Trang 32

HO CHI MINH UNIVERSITY OF INDUSTRY

2.5 Lambda Expressions in C#

– Read as “goes to”

– x=>x+3 if x=1 then 4 is returned

– x=> x==5: if x=5, True is returned

– (x,y)=> x+y if x=2, y=4 then 6 is returned

– (x,y)=>x==y if x=2, y=4 then False is returned

Trang 33

HO CHI MINH UNIVERSITY OF INDUSTRY

2.5.a lambda example

private void button8_Click

( object sender, EventArgs e)

{

ChangeInt d=(( int x)=>x+2); //lambda expression

ChangeInt d1 = (k => k + 2); //lambda expression

ChangeInt d2 = delegate ( int x) //anonymous method

Trang 34

HO CHI MINH UNIVERSITY OF INDUSTRY

2.5.b delegate: turn back to example: lambda

private void btnEven_Click( object sender, EventArgs e)

{

listNumber.SelectItemInListBox(x => x % 2 == 0);

}

Trang 35

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ

Language Integrated Query

LINQ does create a new way of looking at enumerations of data, and

gives out-of-the-box functionality for them

Trang 36

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ example 1

int [] nums = new int [] { 1,1,3,2,5,0,9,8,9};

var result =from n in nums

Output 1 1 3 5 9 9

Trang 37

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 38

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ

 a programming model that introduces queries as a first-class concept

 SQL-like syntax used in LINQ is called a query expression

 provides a set of standard query operators

 common tasks: query, ordered, grouped or aggregated from an existing

in-memory collection, a database, an XML file or many other sources

Trang 39

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ

- Compiler generates code

• More detail: later

string [] list = new string [] { "teo" , "ty" , "bin" , "bo" };

var ret1 = from c in list

where c.StartsWith( "t" )

select c;

IEnumerable < string > ret2 = list.Where(c=>c.StartsWith( "t" ));

Trang 40

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ: Language Integration

var ret1 = from c in list

where c.EndsWith( "o" )

orderby c

select new {Id=c.ElementAt(0),Name=c };

var ret2 = list

Where(c => c.EndsWith( "o" ))

OrderBy(c => c)

Select(c=> new { Id=c.ElementAt(0),Name=c});

string [] list = new string [] { "teo" , "ty" , "bin" , "bo" };

foreach ( var c in ret1){

Console WriteLine(c.Id + " - " +c.Name);

}

Trang 41

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ: LINQ Flavors

Covers many data domains

These implementations is defined through a set of extension methods

The access to these features is controlled by the imported namespaces

Can be extended to support other data domains

Trang 42

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ: Everywhere

 LINQ to Objects, LINQ to SQL, and LINQ to XML

 LINQ is an extendable technology

– open-source product: LINQ Extender

• build your own LINQ extensions

 Other providers

Trang 43

HO CHI MINH UNIVERSITY OF INDUSTRY

3 What is LINQ: Everywhere

Trang 44

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ:

New features of.NET framework support for LINQ:

– Extension methods, lambda expressions

• are used extensively to build queries

– Anonymous types : to allow data to be returned from a query without the need

to first define a class or structure,

– Generics : creation of various types of collection

Trang 45

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 46

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ syntax example

?????

?????

Trang 47

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ basic: Query syntax vs

Method syntax

Performance???

Query syntax => Method syntax

Have to "redeclare" person each time in the lambda expressions query syntax is a lot more readable than method syntax

Trang 48

HO CHI MINH UNIVERSITY OF INDUSTRY

3 LINQ basic: Query syntax vs

Method syntax

• Use the Query Expression syntax wherever possible, its easier to read;

• If you need to mix the Extension Methods with Query Expressions, put them

at the end;

• Keep each part of the Query Expression on separate lines

Trang 49

HO CHI MINH UNIVERSITY OF INDUSTRY

4 LINQ: Exercise

Convert CSV (comma separated values )

string to int array

– S =“20;10;2;0;1;0”

– => array of int {20,10,2,0,1,0}

Trang 50

HO CHI MINH UNIVERSITY OF INDUSTRY

5 LINQ Execution

– Queries that return a single value or object do execute immediately

However, those that return a list of items are usually not executed until the first time that the results are used

Lazy means "don't do the work until you absolutely have to."

Deferred means "don't compute the result until the caller actually uses it."

Trang 51

HO CHI MINH UNIVERSITY OF INDUSTRY

5 LINQ Execution

If you want a query to

be realized immediately, Call ToList, ToArray or any of the other operators that need to enumerate the entire sequence to return a result.

var source = new List < string > { "A" , "B" , "C" };

var values = from c in source

Trang 52

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 53

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 54

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

Foreach

Performs the specified action on each element of the specified array or list (It

doesn’t actually use the System.Predicate delegate Instead, it uses the similar System.Action delegate

Trang 55

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

Exists

Determines whether the specified array or list contains any elements that

match the conditions defined by the specified predicate

Find

Searches for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array or List

Trang 56

HO CHI MINH UNIVERSITY OF INDUSTRY

Searches for an element that matches the conditions defined by the specified

predicate and returns the zero-based index of the first occurrence within the

array

Trang 57

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

FindLast

Searches for an element that matches the conditions defined by the specified

predicate and returns the last occurrence within the entire array or list

FindLastIndex

Searches for an element that matches the conditions defined by the specified predicate and returns the zero-based index of the last occurrence within the array

Trang 58

HO CHI MINH UNIVERSITY OF INDUSTRY

Determines whether every element in the array or list matches the conditions

defined by the specified predicate

Trang 59

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 60

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 61

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 62

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 63

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 64

HO CHI MINH UNIVERSITY OF INDUSTRY

• Returns elements from a sequence as long as a specified condition is true

The element's index is used in the logic of the predicate function

Trang 65

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 66

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 67

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

PetshopDataContext db = new PetshopDataContext ();

var query = ( from p in db.Products

Trang 68

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

//loop through all of the controls

foreach ( Control c in this Controls)

{

//make sure the control is Textbox

if (c is TextBox )

{

//cast that "control" object to the TextBox and disable

}

}

var textBoxes = this Controls.OfType<TextBox>();

this Controls.OfType< TextBox >().ToList().

ForEach(c=>c.Enabled= true );

Trang 69

HO CHI MINH UNIVERSITY OF INDUSTRY

6 LINQ to Object

Trang 70

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 71

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Concepts

 Created to bridge the differences between relational data and CLR object

 Mapping Classes to Tables

– Using code or Graphical Designer for Mapping

– Creating Entity Classes

Tableclass, Rowobject

Trang 72

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Concepts

Using the Graphical Designer for Mapping

– Server connection

– Adding a designer file (dbml): LINQ to SQL Classes

– Drag drop from Server Explorer design surface

Trang 73

HO CHI MINH UNIVERSITY OF INDUSTRY

Right click on project/ add new item / LINQ to SQL classes to create .dbml

Trang 74

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 76

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Concepts

Trang 77

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

PetshopDataContext db = new PetshopDataContext ();

var cateQuery = from cate in db.Categories

Trang 78

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

PetshopDataContext db = new PetshopDataContext ();

Table < Category >cates=db.GetTable< Category >();

var query = from c in cates

Trang 79

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

PetshopDataContext db = new PetshopDataContext ();

var query = db.Categories

Trang 80

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: ActionsInsert

PetshopDataContext db = new PetshopDataContext ();

//create new cate 1 and 2 product

Category cat1 = new Category ();

pro2.Name = "Remote XYZ" ;

cat1.Products.Add(pro1); //add product to cat

cat1.Products.Add(pro2);

db.Categories.InsertOnSubmit(cat1); //add cat

db.SubmitChanges(); //Save database change

Trang 81

HO CHI MINH UNIVERSITY OF INDUSTRY

cat.Name = "New Byard";//Change name

//Ask the DataContext to save all the changes

Trang 82

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 83

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

PetshopDataContext db = new PetshopDataContext ();

var products = db.Products.Where

(p => p.ProductId.Contains( "pro" ));

db.Products.DeleteAllOnSubmit(products);

db.SubmitChanges();

Trang 84

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

PetshopDataContext db = new PetshopDataContext ();

var query = from pro in db.Products

join cat in db.Categories

on pro.CategoryId equals cat.CategoryId

select new

{

Id=pro.ProductId, Name=pro.Name };

Trang 85

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 86

HO CHI MINH UNIVERSITY OF INDUSTRY

Trang 87

PetshopDataContext db = new PetshopDataContext ();

var products = db.GetListProductByCatalog( "birds" );

foreach ( var pro in products)

{

Console WriteLine(pro.Name);

}

Trang 88

HO CHI MINH UNIVERSITY OF INDUSTRY

7 LINQ to SQL: Actions

Trang 89

HO CHI MINH UNIVERSITY OF INDUSTRY

PetshopDataContext db = new PetshopDataContext ();

var query = from p in db.Products

Console WriteLine(c.Pro Name);

foreach ( var l in c.List)

Ngày đăng: 15/03/2014, 15:20

w