Date post: | 26-Aug-2014 |
Category: |
Documents |
Upload: | testingphase |
View: | 1,158 times |
Download: | 0 times |
LINQ
16/10/2008
Agenda
• Impedance Mismatch• C# 3.0 New Features• Introduction to LINQ• LINQ to Objects• LINQ to SQL• LINQ to XML• Summary
Impedance Mismatch•Incompatibility between systems.
•Describes an inadequate ability of one system to accommodate input from another.
Introduction
RDBMS
Business Logic
Windows UI
Web UIConsole
Web Service
Windows Service
Impedance MismatchData Access
C# 3.0 Features
• Implicitly Typed Local Variables• Automatic Properties• Object and Collection Initializers• Anonymous Types• Extension Methods• Lambda Expressions• LINQ
Implicitly Typed Local Variables
• The var keyword
// C# 2.0int x = 5;string name = "Bart Simpson";Dictionary<string, object> data = new Dictionary<string, object>();int size = name.Length;
// C# 3.0var x = 5;var name = "Bart Simpson";var data = new Dictionary<string, object>();var size = name.Length;
var y = x;var keys = data.Keys; // Dictionary<string, object>.KeyCollection
Automatic Propertiespublic class Person { // C# 2.0
private string _firstName, _lastName;
private int _age;
public string FirstName {get { return _firstName; }set { _firstName = value; }
}public string LastName {
get { return _lastName; }set { _lastName = value; }
}public int Age {
get { return _age; }set { _age = value; }
}}
public class Person { // C# 3.0public string FirstName { get;
set; }public string LastName { get; set; }public int Age { get; set; }
}
Object Initializers// C# 2.0
Person p = new Person();p.FirstName = "Bart";p.LastName = "Simpson";p.Age = 12;
// C# 3.0
Person p = new Person() { FirstName = "Bart", LastName = "Simpson", Age = 12
};
Collection Initializers// C# 3.0
List<Person> people = new List<Person>();people.Add(new Person() {
FirstName = "Bart", LastName = "Simpson", Age = 12 });people.Add(new Person() {
FirstName = "Clark", LastName = "Kent", Age = 35 });people.Add(new Person() {
FirstName = "Peter", LastName = "Parker", Age = 30 });// C# 3.0
var people = new List<Person>() {new Person() { FirstName = "Bart", LastName = "Simpson", Age =
12 },new Person() { FirstName = "Clark", LastName = "Kent", Age =
35 },new Person() { FirstName = "Peter", LastName = "Parker", Age =
30 }};
Anonymous Types
var people = new[] {new { FirstName = "Clark", LastName = "Kent", Age = 36 },new { FirstName = "Peter", LastName = "parker", Age = 26 },new { FirstName = "Bart", LastName = "Simpson", Age = 11 }
};
foreach (var i in people)Console.WriteLine("{0} {1} ({2})", i.FirstName, i.LastName,
i.Age);
Console.WriteLine(people[0].GetType().FullName); // ???
In which the type name is generated by the compiler andIs not available at the source code level.
Extension Methods
•Extension methods allows us to “add” method to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
•Extension methods are a special kind of “static” method, but they are called as if they were instance methods.
•The first parameter specifies which type the method operates on, and the parameter is preceded by the “this” modifier.
Extension Methods
public static class MyExtensions {public static string UpperLower(this string str, bool
upperFirst) {StringBuilder newString = new StringBuilder(str.Length);for (int i = 0; i < str.Length; i++) {
newString.Append(upperFirst ? char.ToUpper(str[i]) :char.ToLower(str[i]));
upperFirst = !upperFirst; } return newString.ToString(); }}
string input = Console.ReadLine();Console.WriteLine("calling extension method for {0}: {1}", input,
input.UpperLower(true));
Lambda Expressions
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
var x => x+1; //Implicitly typed expression.
var x => { return x+1;} //Implicitly type statement.
int x => x+1; //Explicitly typed expression.
int x => {return x+1;} //Explicitly type statement.
var prs = Process.GetProcesses() .Where(process => process.WorkingSet64 > 20 * 1024 * 1024) .OrderByDescending(process => process.WorkingSet64) .Select(process => new { process.Id, Name = process.ProcessName });
Extension Extension methodsmethods
Local Local variable type variable type
inferenceinference
Anonymous Anonymous typestypes
Object Object initializersinitializers
Lambda Lambda expressionsexpressions
Language Extensions
Introduction to LINQ• What is LINQ?
• Stands for Language INtegrated Query• Allows developers to query data structures using
SQL-like syntax from within their application’s code• Is available to both C# and Visual Basic developers
in Visual Studio 2008
The LINQ ProjectC# 3.0C# 3.0 Visual Visual
Basic 9.0Basic 9.0 OthersOthers
.NET Language Integrated Query.NET Language Integrated Query
LINQ to ObjectsC# 3.0C# 3.0 Visual Visual
Basic 9.0Basic 9.0 OthersOthers
.NET Language Integrated Query.NET Language Integrated Query
LINQ to Object example• LINQ Example - Querying an array
//Create an array of integersint[] myarray = new int[] { 49, 28, 20, 15, 25, 23, 24, 10, 7, 34 };
//Create a query for odd numbersvar oddNumbers = from i in myarray where i % 2 == 1 select i;
//Display the results of the queryforeach (int i in oddNumbers) Console.WriteLine(i);
//Create a query for odd numbers, sortedvar oddNumbers = from i in myarray where i % 2 == 1 orderby i select i;
//Create a query for odd numbers, sorted in descending ordervar oddNumbers = from i in myarray where i % 2 == 1 orderby i descending select i;
//Create a query for odd numbersvar oddNumbers = from i in myarray where i % 2 == 1 select i;
//Compose the original query to create a query for odd numbersvar sorted = from i in oddNumbers orderby i descending select i;
using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Allen", "Arthur",
"Bennett" }; IEnumerable<string> ayes = names
.Where(s => s[0] == 'A'); foreach (string item in ayes)
Console.WriteLine(item); names[0] = "Bob"; foreach (string item in ayes)
Console.WriteLine(item); }}
Arthur
LINQ to Objects• Native query syntax
in C# and VB– IntelliSense– Autocompletion
• Query Operators can be used against any .NET collection (IEnumerable<T>)
– Select, Where, GroupBy, Join, etc.
• Deferred Query Evaluation
• Lambda Expressions
using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Allen", "Arthur",
"Bennett" }; IEnumerable<string> ayes = names
.Where(s => s[0] == 'A'); foreach (string item in ayes)
Console.WriteLine(item); names[0] = "Bob"; foreach (string item in ayes)
Console.WriteLine(item); }}
AllenArthur
using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor",
"Frank", "Everett", "Albert", "George",
"Harris", "David" }; IEnumerable<string> expr =
from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in expr) Console.WriteLine(item); }}
BURKEDAVIDFRANK
using System;using System.Query;using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor",
"Frank", "Everett", "Albert", "George",
"Harris", "David" }; Func<string, bool> filter = s => s.Length == 5; Func<string, string> extract = s => s; Func<string, string> project = s = s.ToUpper(); IEnumerable<string> expr = names
.Where(filter)
.OrderBy(extract) .Select(project); foreach (string item in expr) Console.WriteLine(item); }}
BURKEDAVIDFRANK
LINQ to SQLC# 3.0C# 3.0 Visual Visual
Basic 9.0Basic 9.0 OthersOthers
.NET Language Integrated Query.NET Language Integrated Query
LINQ to SQL Architecture
ApplicationApplication
LINQ to SQLLINQ to SQL
from c in db.Customerswhere c.City == "London"select c.CompanyName
EnumeratEnumeratee
SELECT CompanyNameFROM CustomerWHERE City = 'London'
SQL QuerySQL Queryor SProcor SProc
RowsRows
ObjectsObjects
db.Customers.Add(c1);c2.City = “Seattle";db.Customers.Remove(c3);
SubmitChanges()SubmitChanges()
INSERT INTO Customer …UPDATE Customer …DELETE FROM Customer …
DML DML or SProcsor SProcs
Querying SQL
SqlConnection c = new SqlConnection(…);SqlConnection c = new SqlConnection(…);c.Open();c.Open();SqlCommand cmd = new SqlCommand(SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone@"SELECT c.Name, c.Phone FROM Customers cFROM Customers c WHERE c.City = @p0");WHERE c.City = @p0");cmd.Parameters["@p0"] = "London";cmd.Parameters["@p0"] = "London";DataReader dr = c.Execute(cmd);DataReader dr = c.Execute(cmd);while (dr.Read()) {while (dr.Read()) { string name = r.GetString(0);string name = r.GetString(0); string phone = r.GetString(1);string phone = r.GetString(1); DateTime date = r.GetDateTime(2);DateTime date = r.GetDateTime(2);}}r.Close();r.Close();
Accessing Accessing relational relational data todaydata today
Queries in Queries in quotesquotes
Loosely Loosely bound bound
argumentsarguments
Loosely Loosely typed result typed result
setssets
No compile No compile time checkstime checks
public class Customer { … }public class Customer { … }
public class Northwind: DataContextpublic class Northwind: DataContext{{ public Table<Customer> Customers;public Table<Customer> Customers; … …}}
Northwind db = new Northwind(…);Northwind db = new Northwind(…);var contacts =var contacts = from c in db.Customersfrom c in db.Customers where c.City == "London"where c.City == "London" select new { c.Name, c.Phone };select new { c.Name, c.Phone };
LINQ to SQLAccessing relational data with LINQAccessing relational data with LINQ
Classes Classes describe datadescribe data
Strongly Strongly typed typed
connectionconnection
Integrated Integrated query syntaxquery syntax
Strongly Strongly typed resultstyped results
Tables are Tables are like like
collectionscollections
Language Extensionsvar contacts = from c in dc.GetTable<customers>() where c.State == "WA" select new { c.Name, c.Phone };
var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone });
Extension Extension methodsmethods
Lambda Lambda expressionsexpressions
Query Query expressionsexpressions
Object Object initializersinitializers
Anonymous Anonymous typestypes
Local Local variable type variable type
inferenceinference
LINQ to XMLC# 3.0C# 3.0 Visual Visual
Basic 9.0Basic 9.0 OthersOthers
.NET Language Integrated Query.NET Language Integrated Query
LINQ to XML
• Large Improvement Over Existing Model• Declarative Model• Supports:
– Creating XML– Loading & querying XML– Modifying & saving XML
LINQ to XML
XmlDocument doc = new XmlDocument();XmlDocument doc = new XmlDocument();XmlElement contacts = doc.CreateElement("contacts");XmlElement contacts = doc.CreateElement("contacts");foreach (Customer c in customers)foreach (Customer c in customers) if (c.Country == "USA") {if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact");XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name");XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName;name.InnerText = c.CompanyName; e.AppendChild(name);e.AppendChild(name); XmlElement phone = doc.CreateElement("phone");XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone;phone.InnerText = c.Phone; e.AppendChild(phone);e.AppendChild(phone); contacts.AppendChild(e);contacts.AppendChild(e); }}doc.AppendChild(contacts);doc.AppendChild(contacts);
Programming XML today
<contacts><contacts> <contact><contact> <name>Great Lakes <name>Great Lakes Food</name>Food</name> <phone>(503) <phone>(503) 555-7123</phone>555-7123</phone> </contact></contact> … …</contacts></contacts>
Imperative Imperative modelmodel
Document Document centriccentric
No integrated No integrated queriesqueries
Memory Memory intensiveintensive
LINQ to XML
XElement contacts = new XElement("contacts",XElement contacts = new XElement("contacts", from c in customersfrom c in customers where c.Country == "USA"where c.Country == "USA" select new XElement("contact",select new XElement("contact", new XElement("name", c.CompanyName),new XElement("name", c.CompanyName), new XElement("phone", c.Phone)new XElement("phone", c.Phone) ))););
Programming XML with LINQDeclarative Declarative
modelmodel
ElementElementcentriccentric
Integrated Integrated queriesqueries
Smaller and Smaller and fasterfaster
Summary• LINQ will be a really important technology.
• Native query integration within languages improves productivity and error checking.
• Using LINQ with ASP.NET is both easy and fun.
• ASP.Net + LINQ - a simple and powerful way to build data driven web applications.
THANK YOU