Your SlideShare is downloading. ×
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05


Published on

This set of slides was used by Ralf Laemmel for a CHOOSE Talk on 05.03.2008

This set of slides was used by Ralf Laemmel for a CHOOSE Talk on 05.03.2008

Published in: Technology, Business
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide
  • Suppose you are an academic Haskell and Prolog nerd as well as a grammar hacker with a sympathy for the real IT world (which equals Cobol, SQL, C++, and more recently, VB, C#, XML). Temporarily bored by the academic treadmill and Haskell's purity, you end up working at Microsoft for some time, which is good timing because Microsoft's LINQ is just taking shape. (I worked in the SQL/XML/LINQ teams at Microsoft, Redmond, 2005-2007.) What is LINQ? Here is my short, unofficial explanation: LINQ (for Language-INtegrated Query) is a programming technology designed to keep it's head above water in the Bermuda triangle of data processing (X/O/R); technically, it is a combination of some cheap OO and functional programming language extensions, an almost unrecognizable stretch of Haskell's list comprehensions, a clever exploit of interface polymorphism, a statically typed + quotation-free form of meta-programming possibly cooler than Lisp, and some noteworthy bits of generative tools and APIs. The functional part of LINQ is immensely important; it's good to see that functional programming is getting into the mainstream. The benefits are clearly not limited to data processing; we will also see major benefits in parallel and distributed programming. My talk touches upon all of the above: it is some mix of LINQ demo, Microsoft retrospection, technical background, technological outlook, and research agenda.
  • Transcript

    • 1. Not quite a sales pitch for C# 3.0 and .NET's LINQ
        • Ralf Lämmel
        • Ex-Microsofty (2005-2007, XML/Data Programmability team)
        • Software Languages Team
        • CS Department, University of Koblenz-Landau
        • Germany
       :=
    • 2. Why LINQ? Because: Data != Objects Aka the Bermuda Triangle of data processing Objects XML Relations
    • 3. What’s LINQ?
      • “ The LINQ Project is a codename for a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. It extends C# and Visual Basic with native language syntax for queries and provides class libraries to take advantage of these capabilities.”
    • 4. Database access in pre-LINQ era SqlConnection c = new SqlConnection(…); c.Open(); SqlCommand cmd = new SqlCommand( @“SELECT c.Name, c.Phone FROM Customers c WHERE c.City = @p0” ); cmd.Parameters[“@po”] = “London”; DataReader dr = c.Execute(cmd); while (dr.Read()) { string name = r.GetString(0); string phone = r.GetString(1); DateTime date = r.GetDateTime(2); } r.Close(); Queries in quotes Arguments loosely bound Results loosely typed Compiler cannot help catch mistakes
    • 5. Database access with LINQ to SQL public class Customer { public int Id; public string Name; public string Phone; … } Table<Customer> customers = db.Customers; var contacts = from c in customers where c.City == &quot;London&quot; select new { c.Name, c.Phone }; Classes describe data Tables are real objects Query is natural part of the language Results are strongly typed
    • 6. XML access in pre-LINQ era public static double XmlOrder2Total(XmlDocument doc) { static string ons = &quot;;; double total = 0.0; XmlElement o = (XmlElement)doc.GetElementsByTagName(&quot;Order&quot;, ons).Item(0); foreach (XmlElement x in o.GetElementsByTagName(&quot;Item&quot;, ons)) { XmlNode priceNode = x.GetElementsByTagName(&quot;Price&quot;, ons).Item(0); XmlNode quantityNode = x.GetElementsByTagName(&quot;Quantity&quot;, ons).Item(0); double priceValue = Double.Parse(priceNode.InnerText); int quantityValue = Int32.Parse(quantityNode.InnerText); total += priceValue * quantityValue; } return total; } Imperative aggregation Low-level namespace model Verbose query API Tedious conversions
    • 7. XML access with LINQ to XML public static double XmlOrder2Total(XElement o) { static XNamespace ons = &quot;;; return (from item in o.Elements(ons + &quot;Item&quot;) select (double)item.Element(ons + &quot;Price&quot;) * (int)item.Element(ons + &quot;Quantity&quot;) ).Sum(); } Functional aggregation Designated type for namespaces SQL/XQuery like query syntax Concise accessors
    • 8. Language INtegrated Query (LINQ) LINQ provides one programming model for all types of data (objects, SQL, XML, DataSets) LINQ enabled data sources LINQ To Objects Objects LINQ To XML <book> <title/> <author/> <price/> </book> XML LINQ enabled ADO.NET LINQ To Datasets LINQ To SQL LINQ To Entities Relational Others… VB C# .NET Language-Integrated Query
    • 9. .NET through the ages
    • 10. The evolution of C# C# 1.0 C# 2.0 C# 3.0 Components on a Managed Runtime Generics Language Integrated Query
    • 11. C# 3.0 design goals
      • Integrate objects, relational data, and XML
      • And
        • Increase conciseness of language
        • Add functional programming constructs
        • Remain 100% backwards compatible
    • 12. C# 3.0 language innovations var contacts = from c in customers where c.City == &quot;Redmond&quot; select new { c.Name, c.Phone }; var contacts = customers .Where(c => c.City == &quot;Redmond&quot;) .Select(c => new { c.Name, c.Phone }); Extension methods Lambda expressions Query expressions Object initializers Anonymous types Local variable type inference
    • 13. Local variable type inference Not to be confused with Pascal
    • 14. Object initializers Field or property assignments
    • 15. Anonymous types class ??? { public string Name; public int Age; } ???
    • 16. Anonymous types class ??? { public string Name; public string Phone; } public class Customer { public string Name; public Address Address; public string Phone; … } public class Contact { public string Name; public string Phone; } Customer c = GetCustomer(…); Contact x = new Contact { Name = c.Name, Phone = c.Phone }; Customer c = GetCustomer(…); var x = new { c.Name, c.Phone }; Customer c = GetCustomer(…); var x = new { Name = c.Name, Phone = c.Phone }; Projection style initializer
    • 17. Lambda expressions – motivating example Delegate type (function type) Higher-order function
    • 18. Lambda expressions (not yet) Non-anonymous function
    • 19. Lambda expressions (C# 1.0/2.0)
    • 20. Lambda expressions (C# 3.0 sugar) Lambda expression
    • 21. Lambda expressions (w/ type inference) Lambda expression
    • 22. Extension methods Static method with “this” argument Invoke It like an instance method
    • 23. Query expressions
      • Queries translate to method invocations
        • Where, Join, OrderBy, Select, GroupBy, …
      from c in customers where c.City == &quot;Redmond&quot; select new { c.Name, c.Phone }; customers .Where(c => c.City == &quot;Redmond&quot; ) .Select(c => new { c.Name, c.Phone });
    • 24. Query expressions from id in source { from id in source | join id in source on expr equals expr [ into id ] | let id = expr | where condition | orderby ordering , ordering , … } select expr | group expr by key [ into id query ] Starts with from Zero or more from , join , let , where , or orderby Ends with select or group by Optional into continuation
    • 25. 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>
    • 26. Extension methods and queries namespace System.Linq { public static class Enumerable { public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) { … } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { … } … } } using System.Linq; Extension methods IEnumerable<string> contacts = customers.Where(c => c.State == &quot;WA&quot;).Select(c => c.Name); Brings extensions into scope obj.Foo(x, y)  ???.Foo(obj, x, y) IntelliSense!
    • 27. Expression trees
    • 28. LINQ architecture System.Linq.Enumerable Delegate based Source implements IEnumerable<T> System.Linq.Queryable Expression tree based Source implements IQueryable<T> SQL DataSets Objects Others…
    • 29. LINQ to SQL Architecture Enumerate SQL Query or SProc Rows Objects SubmitChanges() DML or SProcs Application LINQ to SQL from c in db.Customers where c.City == &quot;London&quot; select c.CompanyName SELECT CompanyName FROM Customer WHERE City = 'London' db.Customers.Add(c1); c2.City = “Seattle&quot;; db.Customers.Remove(c3); INSERT INTO Customer … UPDATE Customer … DELETE FROM Customer …
    • 30. Summary – LINQ contributions
      • Unified query of objects, relational, XML
      • SQL and XQuery-like power natively in C# and VB
      • Type checking, IntelliSense, refactoring for queries
      • Extensibility model for languages and APIs
    • 31. Summary – Related open issues
      • Distribution
      • Conceptual modeling
      • Extensible type systems
      • X/O/R impedance mismatch
    • 32. Demo