Bài giảng Công nghệ lập trình tiên tiến - LINQ

Basic concepts

LINQ requirements

Concepts

Types

LINQ to objects

LINQ to SQL

LINQ to Entity

LINQ to XML

LINQ to Dataset

 

pptx92 trang | Chuyên mục: Lập trình trực quan | Chia sẻ: dkS00TYs | Ngày: 08/06/2015 | Lượt xem: 2237 | Lượt tải: 2download
Tóm tắt nội dung Bài giảng Công nghệ lập trình tiên tiến - LINQ, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
sults 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." 5. LINQ Execution Example deferred 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 { "A","B","C"}; var values = from c in source select c; source.Add("D"); foreach (var c in values) { Console.WriteLine(c); } Out Put: A B C D 6. LINQ to Object Restriction Operators Projection Operators Partitioning Operators Ordering Operators Grouping Operators Set Operators Conversion Operators Element Operators Generation Operators Quantifiers Aggregate Operators Miscellaneous Operators Custom Sequence Operators Query Execution Join Operators Before L2O 6. LINQ to Object – Pre-defined generic delegate • Func • Action • Predicate All Examples, please visit:  6. LINQ to Object Basic extension methods 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. 6. LINQ to Object Basic extension methods 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 6. LINQ to Object Basic extension methods FindAll Retrieves all the elements that match the conditions defined by the specified predicate FindIndex 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 6. LINQ to Object Basic extension methods 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 6. LINQ to Object Basic extension methods RemoveAll Removes the all the elements from the list that match the conditions defined by the specified predicate TrueForAll Determines whether every element in the array or list matches the conditions defined by the specified predicate 6. LINQ to Object Basic extension methods – Select 	• Projection – List a = new List(){1,2,3}; – var u=a.Select(o=>o %2); – Where 	• Filter : var u=a.Where(o=>o %2==0); – OrderBy/OrderByDescending – List a = new List(){1,2,3}; – var u = a.OrderBy(o => o % 2); 6. LINQ to Object Basic extension methods – OfType • Filters the elements of an System.Collections.IEnumerable based on a specified type. – All • Determines whether all elements of a sequence satisfy a condition. 6. LINQ to Object Basic extension methods – Any • Determines whether any element of a sequence satisfies a condition. – Max, Min • Returns the maximum/minimum value in a sequence of nullable System.Decimal values. 6. LINQ to Object Basic extension methods – Single • Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists. SingleOrDefault: … – Skip • Bypasses a specified number of elements in a sequence and then returns the remaining elements. 6. LINQ to Object Basic extension methods – Skipwhile • Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function. 6. LINQ to Object Basic extension methods – Take • Returns a specified number of contiguous elements from the start of a sequence. – TakeWhile • 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. 6. LINQ to Object Basic extension methods – ToArray • Creates an array from a System.Collections.Generic.IEnumerable. – ToDictionary • Creates a Collections.Generic.Dictionary from an System.Collections.Generic.IEnumerable according to a specified key selector function, a comparer, and an element selector function. – ToList • Creates a System.Collections.Generic.List from an System.Collections.Generic.IEnumerable. 6. LINQ to Object Examples int []numbers={3,4,5,1,5}; //query syntax IEnumerable query1 = from num in numbers 	where num % 2 == 0 	orderby num 	select num; //method syntax var query2 = numbers 	 .Where(n => n % 2 == 0) .OrderBy(n => n); 6. LINQ to Object Examples PetshopDataContext db = new PetshopDataContext(); var query = (from p in db.Products where p.Name.StartsWith("b") select new { ProID = p.ProductId, ProName = p.Name } ).Take(3).Skip(1); 6. LINQ to Object Examples //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 ((TextBox)c).Enabled = false; } } var textBoxes = this.Controls.OfType(); this.Controls.OfType().ToList(). 	ForEach(c=>c.Enabled=true); 6. LINQ to Object Exercise 7. LINQ to SQL Concepts • Mapping object • Datacontext Actions • Query • Insert, update, delete • Join • Stored procedure 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 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 Right click on project/ add new item / LINQ to SQL classes to create .dbml 7. LINQ to SQL: Concepts The DataContext – Retrieve objects from database – Track changes – Update from object to database 7. LINQ to SQL: Concepts Translating LINQ to SQL 7. LINQ to SQL: Actions Select data PetshopDataContext db = new PetshopDataContext(); var cateQuery = from cate in db.Categories 	 where cate.Name.StartsWith("B") 	 select cate; var projectionQuery = from c in db.Categories where c.Name.StartsWith("B") select new { ID=c.CategoryId, Name=c.Name }; 7. LINQ to SQL: Actions Select data using System.Data.Linq; PetshopDataContext db = new PetshopDataContext(); Tablecates=db.GetTable(); var query = from c in cates where c.Name.StartsWith("B") || c.Name.EndsWith("d") select new { ID=c.CategoryId, Name=c.Name, List=c.Products }; 7. LINQ to SQL: Actions Select data PetshopDataContext db = new PetshopDataContext(); var query = db.Categories .Where(c => c.Name.StartsWith("b")) .OrderBy(c => c.Name) .Select(c => new { ID=c.CategoryId, Name=c.Name } ); 7. LINQ to SQL: Actions Insert PetshopDataContext db = new PetshopDataContext(); 	//create new cate 1 and 2 product 	Category cat1 = new Category(); 	cat1.CategoryId = "cat1"; 	cat1.Name = "Electronic"; 	Product pro1 = new Product() 	{ ProductId="pro1", 	 Name="Đèn điện" 	}; 	Product pro2 = new Product(); 	pro2.ProductId = "pro2"; 	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 7. LINQ to SQL: Actions Update PetshopDataContext db = new PetshopDataContext(); string id = "byard"; var cat = //Query for specific Cate db.Categories.Single(c=>c.CategoryId==id); cat.Name = "New Byard";//Change name //Ask the DataContext to save all the changes db.SubmitChanges(); 7. LINQ to SQL: Actions Delete PetshopDataContext db = new PetshopDataContext(); string id = "a"; var cat = db.Categories.Single 	(c => c.CategoryId == id); db.Categories.DeleteOnSubmit(cat); db.SubmitChanges(); 7. LINQ to SQL: Actions Delete PetshopDataContext db = new PetshopDataContext(); var products = db.Products.Where 	(p => p.ProductId.Contains("pro")); db.Products.DeleteAllOnSubmit(products); db.SubmitChanges(); 7. LINQ to SQL: Actions Join 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 	}; 7. LINQ to SQL: Actions Using stored procedure USE Petshop GO create proc GetListProductByCatalog @catId varchar(10) as select * from Product where CategoryId=@catId PetshopDataContext db = new PetshopDataContext(); var products = db.GetListProductByCatalog("birds"); foreach (var pro in products) { Console.WriteLine(pro.Name); } 7. LINQ to SQL: Actions Join Table PetshopDataContext db = new PetshopDataContext(); var query = from p in db.Products 	 join it in db.Items on p.ProductId equals it.ProductId into tbl select new { Pro=p, List=tbl }; foreach (var c in query) { Console.WriteLine(c.Pro. Name); foreach (var l in c.List) { Console.WriteLine(" "+l.Name +" - "+l.UnitCost); } Console.WriteLine("---------------------------"); } 7. LINQ to SQL: Actions Relationships Querying Across Relationships PetshopDataContext db = new PetshopDataContext(); var query = from p in db.Products where p.Name.StartsWith("b") select new { ProID = p.ProductId, ProName = p.Name }; 7. LINQ to SQL: Exercise Using L2S – Display data in Listview – Insert new Product record – Update Product record – Delete selected records in list – Button Search Product • L2S • L2O See Next Slide…. Click Icon to download Database Petshop - Khi chạy chương trình lên  load toàn bộ danh mục sản phẩm vào listbox bên trái - Click chuột vào từng danh mục thì hiển thị thông tin danh sách sản phẩm của nó - Click chuột vào từng sản phẩm trong listview thì hiển thị chi tiết thông tin sản phẩm - Double click vào Picturebox để cho phép thay đổi hình ảnh sản phẩm Yêu cầu dùng Cơ sở dữ liệu SQL Server 2008, tên là Petshop (đã nhúng vào slide trước, double vào Icon để mở Cơ sở dữ liệu) END 

File đính kèm:

  • pptx2-Week2-3-4_LINQ.pptx
Tài liệu liên quan