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 1HO CHI MINH UNIVERSITY OF INDUSTRY
LINQ
Language Integrated
Query
Trang 2HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 3HO CHI MINH UNIVERSITY OF INDUSTRY
2 New features in language:
Trang 4HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 5HO 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 6HO 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 7HO 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 8HO 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 9HO CHI MINH UNIVERSITY OF INDUSTRY
public int a2 { set ; get ;}
public int b2 { get ; set ; }
Trang 10HO 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 11HO 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 12HO 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 13HO 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 14HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 15HO CHI MINH UNIVERSITY OF INDUSTRY
2.4 Extension Methods
MessageBox Show(n.SumFrom1toN()+ "" );
Trang 16HO CHI MINH UNIVERSITY OF INDUSTRY
namespace StudyLinQ
{
public static class MyExtensionMethod
{
public static int SumFrom1toN( this int n){…}
Trang 17HO CHI MINH UNIVERSITY OF INDUSTRY
private void btnNoi_Click
( object sender, EventArgs e)
Trang 18HO 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 19HO CHI MINH UNIVERSITY OF INDUSTRY
2.4 Extension Methods
btnColor.ChangeColorToRed();
Trang 20HO 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 21HO CHI MINH UNIVERSITY OF INDUSTRY
2.4.a Delegate
private void btndlg_Click
( object sender, EventArgs e)
Trang 22HO CHI MINH UNIVERSITY OF INDUSTRY
2.4.a delegate: why?
Trang 23HO CHI MINH UNIVERSITY OF INDUSTRY
private void btnEven_Click( object sender, EventArgs e)
Trang 24HO CHI MINH UNIVERSITY OF INDUSTRY
private bool isPrime( int x)
Trang 25HO 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 26HO CHI MINH UNIVERSITY OF INDUSTRY
private bool isEven( int x)
Trang 27HO CHI MINH UNIVERSITY OF INDUSTRY
2.4.a delegate: why?
private void btnEven_Click( object sender, EventArgs e)
Trang 28HO CHI MINH UNIVERSITY OF INDUSTRY
2.4.a delegate: with anonymous
private void button7_Click
( object sender, EventArgs e)
Trang 29HO CHI MINH UNIVERSITY OF INDUSTRY
2.4.a delegate: with anonymous
Exercise:
Trang 30HO 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 31HO 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 32HO 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 33HO 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 34HO 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 35HO 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 36HO 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 37HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 38HO 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 39HO 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 40HO 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 41HO 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 42HO 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 43HO CHI MINH UNIVERSITY OF INDUSTRY
3 What is LINQ: Everywhere
Trang 44HO 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 45HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 46HO CHI MINH UNIVERSITY OF INDUSTRY
3 LINQ syntax example
?????
?????
Trang 47HO 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 48HO 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 49HO 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 50HO 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 51HO 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 52HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 53HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 54HO 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 55HO 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 56HO 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 57HO 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 58HO CHI MINH UNIVERSITY OF INDUSTRY
Determines whether every element in the array or list matches the conditions
defined by the specified predicate
Trang 59HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 60HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 61HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 62HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 63HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 64HO 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 65HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 66HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 67HO CHI MINH UNIVERSITY OF INDUSTRY
6 LINQ to Object
PetshopDataContext db = new PetshopDataContext ();
var query = ( from p in db.Products
Trang 68HO 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 69HO CHI MINH UNIVERSITY OF INDUSTRY
6 LINQ to Object
Trang 70HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 71HO 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
Tableclass, Rowobject
Trang 72HO 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 73HO CHI MINH UNIVERSITY OF INDUSTRY
Right click on project/ add new item / LINQ to SQL classes to create .dbml
Trang 74HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 76HO CHI MINH UNIVERSITY OF INDUSTRY
7 LINQ to SQL: Concepts
Trang 77HO CHI MINH UNIVERSITY OF INDUSTRY
7 LINQ to SQL: Actions
PetshopDataContext db = new PetshopDataContext ();
var cateQuery = from cate in db.Categories
Trang 78HO 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 79HO CHI MINH UNIVERSITY OF INDUSTRY
7 LINQ to SQL: Actions
PetshopDataContext db = new PetshopDataContext ();
var query = db.Categories
Trang 80HO CHI MINH UNIVERSITY OF INDUSTRY
7 LINQ to SQL: Actions Insert
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 81HO CHI MINH UNIVERSITY OF INDUSTRY
cat.Name = "New Byard";//Change name
//Ask the DataContext to save all the changes
Trang 82HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 83HO 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 84HO 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 85HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 86HO CHI MINH UNIVERSITY OF INDUSTRY
Trang 87PetshopDataContext db = new PetshopDataContext ();
var products = db.GetListProductByCatalog( "birds" );
foreach ( var pro in products)
{
Console WriteLine(pro.Name);
}
Trang 88HO CHI MINH UNIVERSITY OF INDUSTRY
7 LINQ to SQL: Actions
Trang 89HO 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)