language i ntegrated query

30
Language INtegrated Query (LINQ)

Upload: mahmoud-ouf

Post on 26-Aug-2014

185 views

Category:

Education


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Language i ntegrated query

Language INtegrated Query

(LINQ)

Page 2: Language i ntegrated query

C# 3.0 Enhancement for LINQ

•Implicitly Typed Local Variables and Arrays

•Object Initializers

•Auto Implemented Properties

•Collection Initializers

•Extension Methods

•Anonymous Types

Page 3: Language i ntegrated query

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

Page 4: Language i ntegrated query

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)));}}

Page 5: Language i ntegrated query

• 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);}

}

Page 6: Language i ntegrated query

• 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);

}}

Page 7: Language i ntegrated query

• 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);}

}

Page 8: Language i ntegrated query

Introduction To LINQ

• 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

Problems in accessing Data from Different DataSource:

Page 9: Language i ntegrated query

LINQ

• Microsoft’s technology to provide a language-level 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)

Page 10: Language i ntegrated query

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.

Page 11: Language i ntegrated query

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.

Page 12: Language i ntegrated query

LINQ Flavors

Page 13: Language i ntegrated query

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.

Page 14: Language i ntegrated query

• 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

LINQ Query Expression(cont.)

Page 15: Language i ntegrated query

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 | ;

Page 16: Language i ntegrated query

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 + " "); }

Page 17: Language i ntegrated query

//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

Page 18: Language i ntegrated query

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);

Page 19: Language i ntegrated query

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

Page 20: Language i ntegrated query

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 currentVideoGameswhere g.Length > 6 orderby g select g;// Print out the results. (Step 3)foreach (string s in subset)

Console.WriteLine("Item: {0}", s);}

Page 21: Language i ntegrated query

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"} };

Page 22: Language i ntegrated query

LINQ to Object(Cont.)• Linq and Generic Collection(Cont.)

// Create a query expression . (Step 2)var fastCars = from c in myCars wherec.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);}

}

Page 23: Language i ntegrated query

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 Firstclass 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"},

Page 24: Language i ntegrated query

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 wherec.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);}

}

Page 25: Language i ntegrated query

LINQ to DataSetDataTable doesn’t implement IEnumerable<T>, so we need to change it to a IEnumerable<T> type.

Obtaining a LINQ-Compatible DataTablepublic 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();

Page 26: Language i ntegrated query

LINQ to DataSet(Cont.)// Project a new result set containing the ID/color for rows with a CarID > 5

var cars = from car in enumDataWhere (int)car["CarID"] > 5select 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);}

}

Page 27: Language i ntegrated query

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 classThis class type is in charge of translating your LINQ query expressions into proper SQL queries as well as communicating with the specified database.

Page 28: Language i ntegrated query

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());

}}

Page 29: Language i ntegrated query

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();

}}

Page 30: Language i ntegrated query