SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3mohamedsamyali
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4mohamedsamyali
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Adam Mukharil Bachtiar
 
Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Yugeswary
 

Mais procurados (20)

C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
DIWE - Advanced PHP Concepts
DIWE - Advanced PHP ConceptsDIWE - Advanced PHP Concepts
DIWE - Advanced PHP Concepts
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
C++ Chapter I
C++ Chapter IC++ Chapter I
C++ Chapter I
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
 
Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)Lab 4 jawapan (sugentiran mane)
Lab 4 jawapan (sugentiran mane)
 
Introducción a LINQ
Introducción a LINQIntroducción a LINQ
Introducción a LINQ
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Bc0037
Bc0037Bc0037
Bc0037
 
Ti1220 Lecture 2
Ti1220 Lecture 2Ti1220 Lecture 2
Ti1220 Lecture 2
 
Algorithm and Programming (Array)
Algorithm and Programming (Array)Algorithm and Programming (Array)
Algorithm and Programming (Array)
 

Destaque

Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroomhales4
 
02.kynangquanlysuthaydoi
02.kynangquanlysuthaydoi02.kynangquanlysuthaydoi
02.kynangquanlysuthaydoiHung Pham Thai
 
tuyển tập thành ngữ ca dao
tuyển tập thành ngữ ca daotuyển tập thành ngữ ca dao
tuyển tập thành ngữ ca daoHung Pham Thai
 
Dan brown angelsanddemons
Dan brown angelsanddemonsDan brown angelsanddemons
Dan brown angelsanddemonsHung Pham Thai
 
Phan huu co phan vi sinh phan u
Phan huu co phan vi sinh phan uPhan huu co phan vi sinh phan u
Phan huu co phan vi sinh phan uHung Pham Thai
 
Pres Outline Da Lat En
Pres Outline Da Lat EnPres Outline Da Lat En
Pres Outline Da Lat EnHung Pham Thai
 
Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Hung Pham Thai
 
Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroomhales4
 
Lunch-time, Life-time - ATD Course Project
Lunch-time, Life-time - ATD Course Project Lunch-time, Life-time - ATD Course Project
Lunch-time, Life-time - ATD Course Project annekcheng
 
San prohibited pesticide list april 2009
San prohibited pesticide list april 2009San prohibited pesticide list april 2009
San prohibited pesticide list april 2009Hung Pham Thai
 
quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)Hung Pham Thai
 
Hmt Health Claims Brussels 1 December Pw
Hmt Health Claims Brussels 1 December PwHmt Health Claims Brussels 1 December Pw
Hmt Health Claims Brussels 1 December Pwpeterwennstrom
 
Progress 4 C Association Workshop Dalat 04122009
Progress 4 C Association Workshop Dalat 04122009Progress 4 C Association Workshop Dalat 04122009
Progress 4 C Association Workshop Dalat 04122009Hung Pham Thai
 
Understanding the Value of a Payments Problem
Understanding the Value of a Payments Problem Understanding the Value of a Payments Problem
Understanding the Value of a Payments Problem Michel van Bommel
 
Phan iii quytrinhkythuatbaovethucvat
Phan iii quytrinhkythuatbaovethucvatPhan iii quytrinhkythuatbaovethucvat
Phan iii quytrinhkythuatbaovethucvatHung Pham Thai
 

Destaque (20)

Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroom
 
Excel 2007
Excel 2007Excel 2007
Excel 2007
 
02.kynangquanlysuthaydoi
02.kynangquanlysuthaydoi02.kynangquanlysuthaydoi
02.kynangquanlysuthaydoi
 
tuyển tập thành ngữ ca dao
tuyển tập thành ngữ ca daotuyển tập thành ngữ ca dao
tuyển tập thành ngữ ca dao
 
Dan brown angelsanddemons
Dan brown angelsanddemonsDan brown angelsanddemons
Dan brown angelsanddemons
 
03 table
03 table03 table
03 table
 
Phan huu co phan vi sinh phan u
Phan huu co phan vi sinh phan uPhan huu co phan vi sinh phan u
Phan huu co phan vi sinh phan u
 
Kn va paem
Kn va paemKn va paem
Kn va paem
 
Pres Outline Da Lat En
Pres Outline Da Lat EnPres Outline Da Lat En
Pres Outline Da Lat En
 
Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009Mr. Thong Presentation Vn 2009
Mr. Thong Presentation Vn 2009
 
Technology In The Classroom
Technology In The ClassroomTechnology In The Classroom
Technology In The Classroom
 
Lunch-time, Life-time - ATD Course Project
Lunch-time, Life-time - ATD Course Project Lunch-time, Life-time - ATD Course Project
Lunch-time, Life-time - ATD Course Project
 
San prohibited pesticide list april 2009
San prohibited pesticide list april 2009San prohibited pesticide list april 2009
San prohibited pesticide list april 2009
 
quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)quất trung bì tập 2 (china chess)
quất trung bì tập 2 (china chess)
 
Hmt Health Claims Brussels 1 December Pw
Hmt Health Claims Brussels 1 December PwHmt Health Claims Brussels 1 December Pw
Hmt Health Claims Brussels 1 December Pw
 
Progress 4 C Association Workshop Dalat 04122009
Progress 4 C Association Workshop Dalat 04122009Progress 4 C Association Workshop Dalat 04122009
Progress 4 C Association Workshop Dalat 04122009
 
Understanding the Value of a Payments Problem
Understanding the Value of a Payments Problem Understanding the Value of a Payments Problem
Understanding the Value of a Payments Problem
 
De b k46_092008
De b k46_092008De b k46_092008
De b k46_092008
 
Phan iii quytrinhkythuatbaovethucvat
Phan iii quytrinhkythuatbaovethucvatPhan iii quytrinhkythuatbaovethucvat
Phan iii quytrinhkythuatbaovethucvat
 
Phu lucb baitap
Phu lucb baitapPhu lucb baitap
Phu lucb baitap
 

Semelhante a Introduction to Linq

Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShakir Majeed Khan
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 
Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01google
 
Practical Models in Practice
Practical Models in PracticePractical Models in Practice
Practical Models in PracticeCHOOSE
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Vagif Abilov
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008Luis Enrique
 
Learning from GOOS - work in progress
Learning from GOOS - work in progressLearning from GOOS - work in progress
Learning from GOOS - work in progressOlaf Lewitz
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLShahriar Hyder
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr-archana-dhawan-bajaj
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Paulo Gandra de Sousa
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyasrsnarayanan
 

Semelhante a Introduction to Linq (20)

Understanding linq
Understanding linqUnderstanding linq
Understanding linq
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01Linq 090701233237 Phpapp01
Linq 090701233237 Phpapp01
 
Greg Demo Slides
Greg Demo SlidesGreg Demo Slides
Greg Demo Slides
 
Practical Models in Practice
Practical Models in PracticePractical Models in Practice
Practical Models in Practice
 
Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#Typed? Dynamic? Both! Cross-platform DSLs in C#
Typed? Dynamic? Both! Cross-platform DSLs in C#
 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
 
Visual studio 2008
Visual studio 2008Visual studio 2008
Visual studio 2008
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Linq
LinqLinq
Linq
 
LINQ.ppt
LINQ.pptLINQ.ppt
LINQ.ppt
 
LINQ
LINQLINQ
LINQ
 
Learning from GOOS - work in progress
Learning from GOOS - work in progressLearning from GOOS - work in progress
Learning from GOOS - work in progress
 
Object Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQLObject Relational Mapping with LINQ To SQL
Object Relational Mapping with LINQ To SQL
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
Dr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slidesDr archana dhawan bajaj - csharp fundamentals slides
Dr archana dhawan bajaj - csharp fundamentals slides
 
Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)Patterns of Enterprise Application Architecture (by example)
Patterns of Enterprise Application Architecture (by example)
 
PoEAA by Example
PoEAA by ExamplePoEAA by Example
PoEAA by Example
 
Linq Sanjay Vyas
Linq   Sanjay VyasLinq   Sanjay Vyas
Linq Sanjay Vyas
 

Mais de Shahriar Hyder

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersShahriar Hyder
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsShahriar Hyder
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion PrincipleShahriar Hyder
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design PatternShahriar Hyder
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketShahriar Hyder
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming FundamentalsShahriar Hyder
 

Mais de Shahriar Hyder (7)

Effective Communication Skills for Software Engineers
Effective Communication Skills for Software EngineersEffective Communication Skills for Software Engineers
Effective Communication Skills for Software Engineers
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFs
 
Dependency Inversion Principle
Dependency Inversion PrincipleDependency Inversion Principle
Dependency Inversion Principle
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Command Design Pattern
Command Design PatternCommand Design Pattern
Command Design Pattern
 
Taking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocketTaking a Quantum Leap with Html 5 WebSocket
Taking a Quantum Leap with Html 5 WebSocket
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
 

Último

Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfTejal81
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0DanBrown980551
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4DianaGray10
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Alkin Tezuysal
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingFrancesco Corti
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptxHansamali Gamage
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInThousandEyes
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxNeo4j
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3DianaGray10
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and businessFrancesco Corti
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)IES VE
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kitJamie (Taka) Wang
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfInfopole1
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...DianaGray10
 

Último (20)

Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdfQ4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
Q4 2023 Quarterly Investor Presentation - FINAL - v1.pdf
 
LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0LF Energy Webinar - Unveiling OpenEEMeter 4.0
LF Energy Webinar - Unveiling OpenEEMeter 4.0
 
UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4UiPath Studio Web workshop series - Day 4
UiPath Studio Web workshop series - Day 4
 
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
Design and Modeling for MySQL SCALE 21X Pasadena, CA Mar 2024
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
Where developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is goingWhere developers are challenged, what developers want and where DevEx is going
Where developers are challenged, what developers want and where DevEx is going
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx.NET 8 ChatBot with Azure OpenAI Services.pptx
.NET 8 ChatBot with Azure OpenAI Services.pptx
 
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedInOutage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
Outage Analysis: March 5th/6th 2024 Meta, Comcast, and LinkedIn
 
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptxEmil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
Emil Eifrem at GraphSummit Copenhagen 2024 - The Art of the Possible.pptx
 
UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3UiPath Studio Web workshop Series - Day 3
UiPath Studio Web workshop Series - Day 3
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and business
 
The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)The Importance of Indoor Air Quality (English)
The Importance of Indoor Air Quality (English)
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
20140402 - Smart house demo kit
20140402 - Smart house demo kit20140402 - Smart house demo kit
20140402 - Smart house demo kit
 
Extra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdfExtra-120324-Visite-Entreprise-icare.pdf
Extra-120324-Visite-Entreprise-icare.pdf
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
 

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
  • 3. How does it work? Standard query operators Query expressions Extension methods Lambda expressions Expression trees Local variable type inference 3
  • 4. 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
  • 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 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
  • 8. 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
  • 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 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
  • 11. 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
  • 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 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 19. 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
  • 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