KEMBAR78
Introduction to Linq | PPT
The LINQ Project
      C#             VB            Others…


     .NET Language Integrated Query

   Standard
                  DLinq              XLinq
    Query
                (ADO.NET)         (System.Xml)
   Operators


                                    <book>
                                      <title/>
                                      <author/>
                                      <year/>
                                      <price/>
                                    </book>




    Objects    SQL        WinFS        XML
Language Integrated Query




                            2
How does it work?
 Standard query operators
 Query expressions
 Extension methods
 Lambda expressions
 Expression trees
 Local variable type inference




                                 3
C# 3.0 Language Innovations
                                                 Query
               var contacts =                 expressions
                 from c in customers
                 where c.State == "WA"
Local variable   select new { c.Name, c.Phone };
type inference

                                 Lambda
                               expressions
             var contacts =
               customers
               .Where(c => c.State == "WA")
               .Select(c => new { c.Name, c.Phone });
Extension
methods          Anonymous                         Object
                   types                         initializers
                                                                4
Lambda Expressions and
Extension Methods




                         5
Object Initializers
                                              Embedded
 public class Rectangle                        objects
 {
   private Point p1 = new Point();
   private Point p2 = new Point();                Read-only
                                                  properties
     public Point P1 { get { return p1; } }
     public Point P2 { get { return p2; } }
 }
            Rectangle r = new Rectangle {
               P1 = { X = 0, Y = 1 },
               P2 = { X = 2, Y = 3 }          No “new Point”
            };


            Rectangle r = new Rectangle();
            r.P1.X = 0;
            r.P1.Y = 1;
            r.P2.X = 2;
            r.P2.Y = 3;

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


   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


                                                                 7
Anonymous Types
 public class Customer
 {
   public string Name;
   public Address Address;         public class Contact
   public string Phone;            {        class ???
   public List<Order> Orders;        public{string Name;
   …                                 public string Phone; Name;
                                               public string
 }                                 }           public string Phone;
Customer c = GetCustomer(…);                }
Contact x = new Contact { Name = c.Name, Phone = c.Phone };

Customer c = GetCustomer(…);
var x = new { Name = c.Name, Phone = c.Phone };

                                              Projection style
Customer c = GetCustomer(…);                     initializer
var x = new { c.Name, c.Phone };


                                                                      8
Query Expressions
  Language integrated query syntax

                            Starts with
                              from          Zero or more
                                           from or where
from id in source
{ from id in source | where condition }         Optional
[ orderby ordering, ordering, … ]               orderby
select expr | group expr by key
[ into id query ]                         Ends with select
                         Optional into      or group by
                         continuation


                                                             9
Query Expressions
 Queries translate to method invocations
   Where, Select, SelectMany, OrderBy, GroupBy

    from c in customers
    where c.State == "WA"
    select new { c.Name, c.Phone };


    customers
    .Where(c => c.State == "WA")
    .Select(c => new { c.Name, c.Phone });

                                             10
C# 3.0 Language Innovations
                               c => c.Name
 Lambda expressions
 Extension methods          static void Dump(this object o);


 Local variable type inference               var x = 5;

 Object initializers     new Point { x = 1, y = 2 }

 Anonymous types                 new { c.Name,
                                 c.Phone }
 Query expressions
                          from … where …
 Expression trees         select

                       Expression<T>
                                                               11
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>
                                                     12
Deferred Query Execution
 Customer[] custs = SampleData.GetCustomers();

  var query = from c in custs where c.City == "London" select c.Name;

       var query = custs.Where(c => c.City == "London").Select(c => c.Name);

                       string[] names = query.ToArray();

custs                                                              names

  ID    Name   Phone
                                 Where                Select



                           c => c.City == "London"   c => c.Name




                                                                               13
DLinq For Relational Data
Accessing data today
                                              Queries in
 SqlConnection c = new SqlConnection(…);       quotes
 c.Open();
 SqlCommand cmd = new SqlCommand(
   @"SELECT c.Name, c.Phone                   Loosely bound
      FROM Customers c                          arguments
      WHERE c.City = @p0");
 cmd.Parameters.AddWithValue("@p0", "London“);
 DataReader dr = c.Execute(cmd);
 while (dr.Read()) {                          Loosely typed
    string name = dr.GetString(0);              result sets
    string phone = dr.GetString(1);
    DateTime date = dr.GetDateTime(2);
 }
 dr.Close();                              No compile
                                         time checks

                                                              14
DLinq For Relational Data
Accessing data with DLinq
                                       Classes
 public class Customer { … }         describe data
 public class Northwind: DataContext
 {                                           Tables are like
   public Table<Customer> Customers;           collections
   …
 }
                                            Strongly typed
                                             connection
 Northwind db = new Northwind(…);
 var contacts =
   from c in db.Customers                 Integrated
   where c.City == "London"              query syntax
   select new { c.Name, c.Phone };
                                       Strongly typed
                                           results
                                                               15
DLinq For Relational Data
 Language integrated data access
   Maps tables and rows to classes and objects
   Builds on ADO.NET and .NET Transactions
 Mapping
   Encoded in attributes
   Relationships map to properties
 Persistence
   Automatic change tracking
   Updates through SQL or stored procedures

                                                 16
XLinq For XML Data
Programming XML today                                        Imperative
                                                               model
 XmlDocument doc = new XmlDocument();
 XmlElement contacts = doc.CreateElement("contacts");                Document
 foreach (Customer c in customers)                                    centric
    if (c.Country == "USA") {
        XmlElement e = doc.CreateElement("contact");
        XmlElement name = doc.CreateElement("name");             No integrated
        name.InnerText = c.CompanyName;                              queries
        e.AppendChild(name);
        XmlElement phone = doc.CreateElement("phone");
        phone.InnerText = c.Phone;                                Memory
        e.AppendChild(phone);      <contacts>                    intensive
        contacts.AppendChild(e);     <contact>
                                       <name>Great Lakes Food</name>
    }                                  <phone>(503) 555-7123</phone>
 doc.AppendChild(contacts);          </contact>
                                      …
                                    </contacts>

                                                                                 17
XLinq For XML Data
Programming XML with XLinq
                                                          Declarative
                                                            model
 XElement contacts = new XElement("contacts",
    from c in customers
    where c.Country == "USA"                                 Element
    select new XElement("contact",                            centric
       new XElement("name", c.CompanyName),
       new XElement("phone", c.Phone)
                                                      Integrated
    )
                                                        queries
 );

                                            Smaller and
                                              faster




                                                                        18
XLinq For XML Data
 Language integrated query for XML
  Expressive power of XPath / XQuery
  But with C# or VB as programming language
 Leverages experience with DOM
  Element centric, not document centric
  Functional construction
  Text nodes are just strings
  Simplified XML namespace support
  Faster and smaller

                                              19
The LINQ Project
 Language Integrated Query for .NET
  Native query syntax in C# 3.0 and VB 9.0

 Standard Query Operators
  SQL-like queries for any .NET collection

 DLinq
  Query enabled data access framework

 XLinq
  Query enabled, smaller, faster XML DOM
                                             20
Benefits Of LINQ
 Unified querying of objects, relational,
 XML

 Type checking and IntelliSense for queries

 SQL and XQuery-like power in C# and VB

 Extensibility model for languages / APIs



                                              21

Introduction to Linq

  • 1.
    The LINQ Project C# VB Others… .NET Language Integrated Query Standard DLinq XLinq Query (ADO.NET) (System.Xml) Operators <book> <title/> <author/> <year/> <price/> </book> Objects SQL WinFS XML
  • 2.
  • 3.
    How does itwork? Standard query operators Query expressions Extension methods Lambda expressions Expression trees Local variable type inference 3
  • 4.
    C# 3.0 LanguageInnovations Query var contacts = expressions from c in customers where c.State == "WA" Local variable select new { c.Name, c.Phone }; type inference Lambda expressions var contacts = customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); Extension methods Anonymous Object types initializers 4
  • 5.
  • 6.
    Object Initializers Embedded public class Rectangle objects { private Point p1 = new Point(); private Point p2 = new Point(); Read-only properties public Point P1 { get { return p1; } } public Point P2 { get { return p2; } } } Rectangle r = new Rectangle { P1 = { X = 0, Y = 1 }, P2 = { X = 2, Y = 3 } No “new Point” }; Rectangle r = new Rectangle(); r.P1.X = 0; r.P1.Y = 1; r.P2.X = 2; r.P2.Y = 3; 6
  • 7.
    Local Variable TypeInference 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” means same type as initializer 7
  • 8.
    Anonymous Types publicclass Customer { public string Name; public Address Address; public class Contact public string Phone; { class ??? public List<Order> Orders; public{string Name; … public string Phone; Name; public string } } public string Phone; Customer c = GetCustomer(…); } Contact x = new Contact { Name = c.Name, Phone = c.Phone }; Customer c = GetCustomer(…); var x = new { Name = c.Name, Phone = c.Phone }; Projection style Customer c = GetCustomer(…); initializer var x = new { c.Name, c.Phone }; 8
  • 9.
    Query Expressions Language integrated query syntax Starts with from Zero or more from or where from id in source { from id in source | where condition } Optional [ orderby ordering, ordering, … ] orderby select expr | group expr by key [ into id query ] Ends with select Optional into or group by continuation 9
  • 10.
    Query Expressions Queriestranslate to method invocations Where, Select, SelectMany, OrderBy, GroupBy from c in customers where c.State == "WA" select new { c.Name, c.Phone }; customers .Where(c => c.State == "WA") .Select(c => new { c.Name, c.Phone }); 10
  • 11.
    C# 3.0 LanguageInnovations c => c.Name Lambda expressions Extension methods static void Dump(this object o); Local variable type inference var x = 5; Object initializers new Point { x = 1, y = 2 } Anonymous types new { c.Name, c.Phone } Query expressions from … where … Expression trees select Expression<T> 11
  • 12.
    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> 12
  • 13.
    Deferred Query Execution Customer[] custs = SampleData.GetCustomers(); var query = from c in custs where c.City == "London" select c.Name; var query = custs.Where(c => c.City == "London").Select(c => c.Name); string[] names = query.ToArray(); custs names ID Name Phone Where Select c => c.City == "London" c => c.Name 13
  • 14.
    DLinq For RelationalData Accessing data today Queries in SqlConnection c = new SqlConnection(…); quotes c.Open(); SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone Loosely bound FROM Customers c arguments WHERE c.City = @p0"); cmd.Parameters.AddWithValue("@p0", "London“); DataReader dr = c.Execute(cmd); while (dr.Read()) { Loosely typed string name = dr.GetString(0); result sets string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2); } dr.Close(); No compile time checks 14
  • 15.
    DLinq For RelationalData Accessing data with DLinq Classes public class Customer { … } describe data public class Northwind: DataContext { Tables are like public Table<Customer> Customers; collections … } Strongly typed connection Northwind db = new Northwind(…); var contacts = from c in db.Customers Integrated where c.City == "London" query syntax select new { c.Name, c.Phone }; Strongly typed results 15
  • 16.
    DLinq For RelationalData Language integrated data access Maps tables and rows to classes and objects Builds on ADO.NET and .NET Transactions Mapping Encoded in attributes Relationships map to properties Persistence Automatic change tracking Updates through SQL or stored procedures 16
  • 17.
    XLinq For XMLData Programming XML today Imperative model XmlDocument doc = new XmlDocument(); XmlElement contacts = doc.CreateElement("contacts"); Document foreach (Customer c in customers) centric if (c.Country == "USA") { XmlElement e = doc.CreateElement("contact"); XmlElement name = doc.CreateElement("name"); No integrated name.InnerText = c.CompanyName; queries e.AppendChild(name); XmlElement phone = doc.CreateElement("phone"); phone.InnerText = c.Phone; Memory e.AppendChild(phone); <contacts> intensive contacts.AppendChild(e); <contact> <name>Great Lakes Food</name> } <phone>(503) 555-7123</phone> doc.AppendChild(contacts); </contact> … </contacts> 17
  • 18.
    XLinq For XMLData Programming XML with XLinq Declarative model XElement contacts = new XElement("contacts", from c in customers where c.Country == "USA" Element select new XElement("contact", centric new XElement("name", c.CompanyName), new XElement("phone", c.Phone) Integrated ) queries ); Smaller and faster 18
  • 19.
    XLinq For XMLData Language integrated query for XML Expressive power of XPath / XQuery But with C# or VB as programming language Leverages experience with DOM Element centric, not document centric Functional construction Text nodes are just strings Simplified XML namespace support Faster and smaller 19
  • 20.
    The LINQ Project Language Integrated Query for .NET Native query syntax in C# 3.0 and VB 9.0 Standard Query Operators SQL-like queries for any .NET collection DLinq Query enabled data access framework XLinq Query enabled, smaller, faster XML DOM 20
  • 21.
    Benefits Of LINQ Unified querying of objects, relational, XML Type checking and IntelliSense for queries SQL and XQuery-like power in C# and VB Extensibility model for languages / APIs 21