c# 3.0 & linq
DESCRIPTION
C# 3.0 & LINQ. 2007.11.24. Microsoft Visual C# MVP 한용희 http://blog.naver.com/woom333. Agenda. C# 3.0 New Features Local Variable Type Inference Object / Collection Initializers Anonymous Types Extension Methods Lambda Expressions Query Expressions LINQ LINQ to SQL LINQ to XML - PowerPoint PPT PresentationTRANSCRIPT
Agenda
• C# 3.0 New Features– Local Variable Type Inference– Object / Collection Initializers– Anonymous Types– Extension Methods– Lambda Expressions– Query Expressions
• LINQ– LINQ to SQL– LINQ to XML– LINQ to Entities– LINQ to DataSet
C# 3.0Part 1
Enums
Expression Trees
Type Safety
GenericsGenerics
IteratorsIterators
Nullable Types
Nullable Types
Anonymous Methods
Anonymous Methods
Managed
Object Oriented
Accessors
Reflection
delegatesObject Initializers
Anonymous Classes
Lambda Expressions
Extension Methods
Local Var’s Type
InferenceLINQ
Partial ClassesPartial
Classes
C# 1.0 , 2.0, 3.0
Why C# 3.0Why C# 3.0
New Features
• Local Variable Type Inference
• Object / Collection Initializers
• Anonymous Types
• Extension Methods
• Lambda Expressions
• Query Expressions
Local Variable Type Inference
int i = 5;string s = "Hello";double d = 1.0;int[] numbers = new int[] {1, 2, 3};Dictionary<int,Order> orders = new Dictionary<int,Order>();
int i = 5;string s = "Hello";double d = 1.0;int[] numbers = new int[] {1, 2, 3};Dictionary<int,Order> orders = new Dictionary<int,Order>();
var i = 5;var s = "Hello";var d = 1.0;var numbers = new int[] {1, 2, 3};var orders = new Dictionary<int,Order>();
var i = 5;var s = "Hello";var d = 1.0;var numbers = new int[] {1, 2, 3};var orders = new Dictionary<int,Order>();
“var” means same type as initializer“var” means same type as initializer
Object / Collection Initializers
public class Point{ public int x, y;}
public class Point{ public int x, y;}
Point a = new Point { x = 0, y = 1};Point a = new Point { x = 0, y = 1};
Point a = new Point();a.x = 0;a.y = 1;
Point a = new Point();a.x = 0;a.y = 1;
Field or property assignments
Object / Collection initializers
List<int> powers = new List<int> { 1, 10, 100, 1000, 10000 };List<int> powers = new List<int> { 1, 10, 100, 1000, 10000 };
Must implement ICollection<T>Must implement ICollection<T>
List<int> powers = new List<int>();powers.Add(1);powers.Add(10);powers.Add(100);powers.Add(1000);powers.Add(10000);
List<int> powers = new List<int>();powers.Add(1);powers.Add(10);powers.Add(100);powers.Add(1000);powers.Add(10000);
Anonymous Types
var x = new { a = 3, b = 5, c = “some text” };var x = new { a = 3, b = 5, c = “some text” };
class __Anonymous1{
private int _a = 3;private int _b = 5;private string _c = “some text”;
public int a { get { return v1; } set { _a = value; } }public int b { get { return v2; } set { _b = value; } }public int c { get { return v3; } set { _c = value; } }
}
class __Anonymous1{
private int _a = 3;private int _b = 5;private string _c = “some text”;
public int a { get { return v1; } set { _a = value; } }public int b { get { return v2; } set { _b = value; } }public int c { get { return v3; } set { _c = value; } }
}
Fits with complex temporarily variables
Extension Methods
public static class Extensions{ public static int ToInt32(this string s) { return Int32.Parse(s); }}
public static class Extensions{ public static int ToInt32(this string s) { return Int32.Parse(s); }}
string s="1234";int i = s.ToInt32(); // Same as Extensions.ToInt32(s)string s="1234";int i = s.ToInt32(); // Same as Extensions.ToInt32(s)
• The ability to extend existing types.– Add new functions to existing classes.
– No need for editing the existing codes.
• Simpler than inheritance.– Inheritance will not work with sealed or primitive types.
– Inheritance is limited by class accessibility.
Lamda Expressions
• Old Programming Concept (λ-calculus).
• Exists in most dynamic languages .– Python, Lisp, Ruby
• Evolution of anonymous functions.
Func<int, int> increment = i => i+1;Increment(10); // result is 11
<Delegate Type> identifier = (<param list>) => <Expression>
Lamda Expressions
delegate string SomeDelegate(string s);delegate string SomeDelegate(string s);
static string TestMethod1(string s){ return s.ToUpper();}…
SomeDelegate d1 = new SomeDelegate(TestMethod1);string a = d1(“abcde");
static string TestMethod1(string s){ return s.ToUpper();}…
SomeDelegate d1 = new SomeDelegate(TestMethod1);string a = d1(“abcde");
SomeDelegate d2 = delegate(string s){
return s.ToUpper();};string a = d2("abcde");
SomeDelegate d2 = delegate(string s){
return s.ToUpper();};string a = d2("abcde");
SomeDelegate d3 = s => s.ToUpper();string a = d3("abcde");SomeDelegate d3 = s => s.ToUpper();string a = d3("abcde");
Implicitly typedImplicitly typed
C# 1.0
C# 2.0
C# 3.0
Query Expressions
var contacts = from c in customers where c.City == “London" select new { c.CustomerID, c.City };
var contacts = customers .Where(c => c.City == “London") .Select(c => new { c.CustomerID, c.City });
Extension methodsExtension methods
Lambda expressionsLambda expressions
Query expressionsQuery expressions
Object initializersObject initializers
Anonymous typesAnonymous types
Implicitly typed Local variableImplicitly typed Local variable
Language INtegrated Query(LINQ)Part 2
Problems
OOP, Inheritance, Polymorphism, Loops,
Conditions …etc(Imperative)
OOP, Inheritance, Polymorphism, Loops,
Conditions …etc(Imperative)
Projection, Join, Grouping, Queries
(Declarative)
Projection, Join, Grouping, Queries
(Declarative)
LINQ Project Goals
• Unified programming model for any data type– Database Relational Data
– XML Files
– Collections & Arrays
• Introduce more declarative syntax– Helps the system find the best execution strategy
• Parallel LINQ (PLINQ)
The LINQ Project
C# 3.0 VB 9.0 Others
.NET Language Integrated Query
LINQ to
DataSets
LINQ to
DataSets
LINQ to
Entities
LINQ to
Entities
LINQ to
Objects
LINQ to
Objects
Objects
LINQ to
XML
LINQ to
XML
<book> <title/> <author/> <year/> <price/></book>
XML
Relational
LINQ to
SQL
LINQ to
SQL
LINQ to SQL
SqlConnection c = new SqlConnection(…);c.Open();SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone FROM Customers c WHERE c.City = @p0");cmd.Parameters.AddWithValue("@p0", "London“);DataReader dr = c.Execute(cmd);while (dr.Read()) { string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2);}dr.Close();
SqlConnection c = new SqlConnection(…);c.Open();SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone FROM Customers c WHERE c.City = @p0");cmd.Parameters.AddWithValue("@p0", "London“);DataReader dr = c.Execute(cmd);while (dr.Read()) { string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2);}dr.Close();
Accessing data todayQueries in quotesQueries in quotes
Loosely bound argumentsLoosely bound arguments
Loosely typed result setsLoosely typed result sets
No compile time checksNo compile time checks
public class Customer { … }
public class Northwind: DataContext{ public Table<Customer> Customers; …}
public class Customer { … }
public class Northwind: DataContext{ public Table<Customer> Customers; …}
Northwind db = new Northwind(…);var contacts = from c in db.Customers where c.City == "London" select new { c.Name, c.Phone };
Northwind db = new Northwind(…);var contacts = from c in db.Customers where c.City == "London" select new { c.Name, c.Phone };
LINQ to SQL
Accessing data with LINQ to SQLClasses describe dataClasses describe data
Strongly typed connectionStrongly typed connection
Integrated query syntaxIntegrated query syntax
Strongly typed resultsStrongly typed results
Tables are like collectionsTables are like collections
LINQ to SQL Architecture
from c in db.Customerswhere c.City == "London"select c.CompanyName
Enumerate
SELECT CompanyNameFROM CustomerWHERE City = 'London'
SQL Queryor SProc
Rows
Objects
db.Customers.Add(c1);c2.City = “Seattle";db.Customers.Remove(c3);
SubmitChanges()
INSERT INTO Customer …UPDATE Customer …DELETE FROM Customer …
DML or SProcs
Standard Query Operators
Restriction Where
Projection Select, SelectMany
Ordering OrderBy, ThenBy
Grouping GroupBy
Quantifiers Any, All
Partitioning Take, Skip, TakeWhile, SkipWhile
Sets Distinct, Union, Intersect, Except
Elements First, FirstOrDefault, ElementAt
Aggregation Count, Sum, Min, Max, Average
Conversion ToArray, ToList, ToDictionary
Casting OfType<T>
LINQ to XML
XmlDocument doc = new XmlDocument();XmlElement contacts = doc.CreateElement("contacts");foreach (Customer c in customers) if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName; e.AppendChild(name); XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone; e.AppendChild(phone); contacts.AppendChild(e); }doc.AppendChild(contacts);
XmlDocument doc = new XmlDocument();XmlElement contacts = doc.CreateElement("contacts");foreach (Customer c in customers) if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name"); name.InnerText = c.CompanyName; e.AppendChild(name); XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone; e.AppendChild(phone); contacts.AppendChild(e); }doc.AppendChild(contacts);
Programming XML today
<contacts> <contact> <name>Great Lakes Food</name> <phone>(503) 555-7123</phone> </contact> …</contacts>
<contacts> <contact> <name>Great Lakes Food</name> <phone>(503) 555-7123</phone> </contact> …</contacts>
Imperative modelImperative model
Document centricDocument centric
No integrated queriesNo integrated queries
Memory intensiveMemory intensive
LINQ to XML
XElement contacts = new XElement("contacts", from c in customers where c.Country == "USA" select new XElement("contact", new XElement("name", c.CompanyName), new XElement("phone", c.Phone) ));
XElement contacts = new XElement("contacts", from c in customers where c.Country == "USA" select new XElement("contact", new XElement("name", c.CompanyName), new XElement("phone", c.Phone) ));
Programming XML with XLinqDeclarative modelDeclarative model
ElementcentricElementcentric
Integrated queriesIntegrated queries
Smaller and fasterSmaller and faster
Guidance for LINQ to Relational Data
• LINQ to SQL – Strongly Typed Database– Emphasis on rapid application development– Direct mapping to Microsoft SQL Server family of databases– Release in Microsoft Visual Studio 2008 RTM
• LINQ to Entities – Flexible mapping to existing Schema– Focus on enterprise-grade data scenarios– Flexible Mapping to Microsoft SQL Server and third-party databases– Release in Microsoft Visual Studio 2008 update
• CTPs on top of Microsoft Visual Studio 2008 Betas/RTM
• LINQ to DataSet – In-Memory Cache w/Change Tracking– All the scenarios where DataSet is useful today
• Offline, Disconnected, Aggregation• Change Tracking
..Plus support for Query Operations– Strongly typed or Untyped DataSet Support– Release in Microsoft Visual Studio 2008 RTM
LINQ to SQLStrongly typed SQL Database
• Design Points– Rapid Development against SQL Database
• Direct Mapping to SQL Server Schema• Mappings expressed in Attributes or XML file
– "Just Work" for common scenarios• Execute when needed• Naming Conventions
– Business Logic– Custom Insert/Update/Delete operations
– Minimally Intrusive object model– Provide Customization, Optimizations where required
• Targets: Microsoft SQL Server• RTM: Microsoft Visual Studio 2008 RTM
LINQ to SQLDirect Mapping
• Direct Mapping• Each class maps to a single SQL Schema Object
• Table, View
• Stored Procedure, Table Valued Function
• Simple renaming of Tables, Columns
• Foreign Keys can be expressed as Relationships• Properties to navigate in query, results
• Inheritance• Multiple Classes in a Hierarchy can map to a single
Table/View/Stored Proc/TVF with a discriminator column
LINQ to SQLFeatures
• Customization– Business Logic
• Partial classes for generated Objects– Add Methods, non-persistent members, etc.
– Business Logic through Partial methods based on naming conventions
– Update Logic• Implement partial methods in derived Class
– Call Stored Procedures or invoke custom logic
• Optimizations– Loading Options
• ObjectTrackingEnabled
• DeferredLoadingEnabled
– Compiled Query
• Save overhead of SQL generation from Language Expression
LINQ to EntitiesFlexible Mapping to Relational Data
• Design Points• Flexible Mapping to Existing Relational Schema
• Well defined Conceptual model• Share common model across products (Reporting, Analysis, etc…)
• Declarative Mapping between Application and Store• Allows Storage Schema and Application to evolve independently
• Explicit Operations• Server interactions should be explicit
• Build implicit logic on top of explicit operations
• Common Textual "EntitySQL" Language for Ad-Hoc queries
• Targets: Microsoft SQL Server and third-party databases• RTM: Microsoft Visual Studio 2008 Update H1CY08
LINQ to EntitiesFlexible Mapping to Relational Data
• Flexible Mapping• Mapping a single class to multiple tables/views• Mapping to different types of inheritance
• Single Table per Class Hierarchy• Separate Table for each Class in a Hierarchy• Shared Table for Base Class members in a Hierarchy
• Complex (composite) types• i.e., Street, City, Region, and Zip as "Address"
• Directly mapping Many:Many relationships• Mapping to an arbitrary Query
• Store Query• Expose arbitrary store query as a storage Table
• Entity Query• Express mapping as EntitySQL against storage schema
LINQ to EntitiesFeatures
• Customization• Business Logic
• Partial Classes, Events, Partial Methods
• Update Logic• Generated Update Views• Declarative stored procedures
• Optimizations• NoTracking
• Extensibility• Partitioning of Metadata• Flexible Runtime Mapping• Metadata Pluggability
LINQ to DataSetLINQ over Disconnected Cache with Change Tracking
• Disconnected Cache– Offline/Remote
– Data Aggregation
– Application Data
All with Change Tracking
• Queryable– Filter, Projection
– Joins
• Across Tables
• Other in-Memory sources
– Local expressions
All through Common LINQ syntax
• RTM: Microsoft Visual Studio 2008 RTM
LINQ to DataSetTyped and UnTyped
• Untyped DataSet– Call AsEnumerable() on DataTable
– Reference Fields by Name
• Use Field<T>(columnName)– Project out fields for strongly typed result
• Typed DataSet– Use strongly typed accessors
var query = from row in myDataSet.Tables["Customers"].AsEnumerable() where row .Field<string>("City") == "London" select new { row.Field <string> ("CustomerID"),
row.Field <string> ("ContactName") } ;
var query = from customer in northwind.Customers where customer.City == "London" select customer;