Your SlideShare is downloading. ×
  • Like
Language i ntegrated query
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Language i ntegrated query

  • 123 views
Published

 

Published in Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
123
On SlideShare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
4
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Language INtegrated Query (LINQ)
  • 2. C# 3.0 Enhancement for LINQ •Implicitly Typed Local Variables and Arrays •Object Initializers •Auto Implemented Properties •Collection Initializers •Extension Methods •Anonymous Types
  • 3. Example: A Common Code developer wants to create a generic method for filtering an array of integers, but with the ability to specify the algorithm for filtration to the Application developer
  • 4. Solution • The Common Code Developer: public delegate bool IntFilter(int i); public class Common { public static int[] FilterArray(int[] ints, IntFilter filter) { ArrayList aList = new ArrayList(); foreach(int I in ints) { if(filter(i)) {aList.Add(i);} } return((int[])aList.ToArray(typeof(int))); } }
  • 5. • The Application Code Developer (I) Class MyApplication { public static bool IsOdd(int i) { return ((i % 2)==1); } public static void Main() { int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] fnum = Common.FilterArray(nums, MyApplication.IsOdd); foreach(int i in fnum) Console.WriteLine(i); } }
  • 6. • The Application Code Developer, Anonymous method “C#2.0” (II) Class MyApplication { public static void Main() { int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] fnum = Common.FilterArray(nums, delegate(int i) {return((i%2)==1);}); foreach(int i in fnum) Console.WriteLine(i); } }
  • 7. • The Application Code Developer, Lambda Expression “C#3.0” (III) Class MyApplication { public static void Main() { int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] fnum = Common.FilterArray(nums, j=>((j % 2)==1)); foreach(int i in fnum) Console.WriteLine(i); } }
  • 8. Introduction To LINQ Problems in accessing Data from Different DataSource: • We Can’t programmatically interact with a database at the native language level • Trouble caused by conflict data types utilized versus the native language of the program
  • 9. LINQ • Microsoft’s technology to provide a languagelevel support mechanism for querying data of all types. – in-memory arrays and collections, – databases, – XML documents, and more. • The returned Set of objects is called “sequence” • Most sequence are of type IEnumerable<T> • LINQ is not for query as in its name, We can better think of it as Data Integration Engine (DIE)
  • 10. LINQ Definition • LINQ is a uniform programming model for any kind of data. • LINQ enables you to query and manipulate data with a consistent model that is independent from data sources. • LINQ is just another tool for embedding SQL queries into code. • LINQ is yet another data abstraction layer.
  • 11. LINQ Definition (Cont.) LINQ is all the previous and more •LINQ is a methodology that simplifies and unifies the implementation of any kind of data access. •LINQ does not force you to use a specific architecture; it facilitates the implementation of several existing architectures for accessing data.
  • 12. LINQ Flavors
  • 13. LINQ Query Expression • Query expressions are written in a declarative query syntax introduced in C# 3.0 • Use the same basic query expression patterns to query and transform data in SQL databases, ADO.NET Datasets, XML documents and streams, and .NET collections • All LINQ query operations consist of three distinct actions: 1. Obtain the data source. 2. Create the query. 3. Execute the query.
  • 14. LINQ Query Expression(cont.) • LINQ use deffered execution: • A query is not executed until you iterate over the query variable in a foreach statement, this is named deffered execution. • The benefit of this approach is that you are able to apply the same LINQ query multiple times to the same container, and rest assured you are obtaining the latest and greatest results
  • 15. LINQ Query Expression(cont.) • The general form of the query expression is: from id in source {Where condition | Orderby ordering, ordering, ... [Ascending | Descending] } Select expr | ;
  • 16. class LINQQueryExpressions { static void Main() { // Specify the data source. int[] scores = new int[] { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); }
  • 17. //Make a change Scores[0] = 50; Console.WriteLine(); // Re-Execute the query. foreach (int i in scoreQuery) { Console.Write(i + " "); } } } // Output: 97 92 81 // 92 81
  • 18. LINQ Query using Expression Tree • We can write the Query Expression is by using Expression Tree in aid with Standard Query Operator (SQO) // Define the query expression. IEnumerable<int> scoreQuery = scores.Where(i=>i>80).Select(i=>i);
  • 19. Standard Query Operator (SQO) • SQO is an API provided by LINQ to enables querying of any .NET array or collection. • All SQO are extension methods defined in System.Linq.Enumerable class which inherit from Ienumerable<T> interface • SQO returning a singleton value (Max, Min,...) executes immediately • SQO returning a sequence are deferred executed
  • 20. LINQ to Object • Linq and Array static void QueryOverStrings() { // Assume we have an array of strings. (Step 1) string[] currentVideoGames = {"Morrowind", "BioShock", "Half Life 2: Episode 1", "The Darkness", "Daxter", "System Shock 2"}; // Build a query expression to represent the items in the array // that have more than 6 letters. (Step 2) IEnumerable<string> subset = from g in currentVideoGames where g.Length > 6 orderby g select g; // Print out the results. (Step 3) foreach (string s in subset) Console.WriteLine("Item: {0}", s); }
  • 21. LINQ to Object(Cont.) • Linq and Generic Collection class Car { public string PetName = string.Empty; public string Color = string.Empty; public int Speed; public string Make = string.Empty; } static void Main(string[] args) { // Make a List<> of Car objects using object init syntax. (Step 1) List<Car> myCars = new List<Car>() { new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"}, new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} };
  • 22. LINQ to Object(Cont.) • Linq and Generic Collection(Cont.) // Create a query expression . (Step 2) var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c; //Execute the Query. (Step 3) foreach (var car in fastCars) { Console.WriteLine("{0} is going too fast!", car.PetName); } }
  • 23. LINQ to Object(Cont.) • Linq and Non-Generic Collection LINQ are designed to work with any type implementing IEnumerable<T>, The Non-Generic collection doesn’t implement IEnumerable<T>. So, need to transform it to a Generic Collection First class Car { public string PetName = string.Empty; public string Color = string.Empty; public int Speed; public string Make = string.Empty; } static void Main(string[] args) { // Make a List<> of Car objects using object init syntax. (Step 1) ArrayList<Car> myCars = new ArrayList<Car>() { new Car{ PetName = "Henry", Color = "Silver", Speed = 100, Make = "BMW"}, new Car{ PetName = "Daisy", Color = "Tan", Speed = 90, Make = "BMW"},
  • 24. LINQ to Object(Cont.) • Linq and Non-Generic Collection(Cont.) new Car{ PetName = "Mary", Color = "Black", Speed = 55, Make = "VW"}, new Car{ PetName = "Clunker", Color = "Rust", Speed = 5, Make = "Yugo"}, new Car{ PetName = "Melvin", Color = "White", Speed = 43, Make = "Ford"} }; // Transform ArrayList into an IEnumerable<T>-compatible type. IEnumerable<Car> myCarsEnum = myCars.OfType<Car>(); // Create a query expression . (Step 2) var fastCars = from c in myCars where c.Speed > 90 && c.Make == "BMW" select c; //Execute the query. (Step 3) foreach (var car in fastCars) { Console.WriteLine("{0} is going too fast!", car.PetName); } }
  • 25. LINQ to DataSet DataTable doesn’t implement IEnumerable<T>, so we need to change it to a IEnumerable<T> type. Obtaining a LINQ-Compatible DataTable public static void Main { // Get a DataTable containing the current Inventory // of the AutoLot database. InventoryDALDisLayer dal = new InventoryDALDisLayer(@"Data Source = (local)SQLEXPRESS;Initial Catalog=AutoLot;" + "Integrated Security=True"); DataTable data = dal.GetAllInventory(); // Get enumerable version of DataTable. EnumerableRowCollection enumData = data.AsEnumerable(); // OR Store return value as IEnumerable<T>. IEnumerable<DataRow> enumData = data.AsEnumerable(); //OR Store return value implicitly. var enumData = data.AsEnumerable();
  • 26. LINQ to DataSet(Cont.) // Project a new result set containing the ID/color for rows with a CarID > 5 var cars = from car in enumData Where (int)car["CarID"] > 5 select new { ID = (int)car["CarID"], Color = (string)car*"Color“+}; Console.WriteLine("Cars with ID greater than 5:"); foreach (var item in cars) { Console.WriteLine("-> CarID = {0} is {1}", item.ID, item.Color); } }
  • 27. LINQ to SQL • Entity Class Entity classes are types that represent the relational data you wish to interact with. Programmatically speaking, entity classes are class definitions that are annotated with various LINQ to SQL attributes (such as [Table] and [Column]) that map to a physical table in a specific database. • DataContext class This class type is in charge of translating your LINQ query expressions into proper SQL queries as well as communicating with the specified database.
  • 28. Example: [Table] public class Inventory { [Column] public string Make; [Column] public string Color; [Column] public string PetName; // Identify the primary key. [Column(IsPrimaryKey = true)] public int CarID; public override string ToString() { return string.Format("ID = {0}; Make = {1}; Color = {2}; PetName = {3}", CarID, Make.Trim(), Color.Trim(), PetName.Trim()); } }
  • 29. Example (Cont.) class Program { const string cnStr = @"Data Source=(local)SQLEXPRESS;Initial Catalog=AutoLot;" + "Integrated Security=True"; static void Main(string[] args) { // Create a DataContext object. DataContext db = new DataContext(cnStr); // Now create a Table<> type. Table<Inventory> invTable = db.GetTable<Inventory>(); // Show all data using a LINQ query. Console.WriteLine("-> Contents of Inventory Table from AutoLot database:n"); foreach (var car in from c in invTable select c) Console.WriteLine(car.ToString()); Console.ReadLine(); } }