LINQ by ewghwehws



Nick Randolph
The LINQ Project
      VB             C#            Others…

     .NET Language Integrated Query

                  DLinq              XLinq
                (ADO.NET)         (System.Xml)


    Objects    SQL        WinFS        XML
What is LINQ ?
 .NET Language Integrated Query
 Allows you to write TSQL style queries
 when working with Objects, XML or data.
 Conjunction of language features and
 framework features. Relies heavily on
 language compilers.
An Example of LINQ
  Class Customer
    Public Name As String
    Public Country As String
  End Class

  Dim result = Select Distinct cust.Country _
              From cust In customers _
              Order By Country

 Note: Result is as OrderedSequence(Of T), in this case T is as String
Query Comprehensions
Project     Select <expr>
Filter      Where <expr>
Test        Any(<expr>), All(<expr>)
Join        <expr> [ [ Left | Right ] Outer ] Join <expr> On <expr>
Group       Group By <expr>
Aggregate   Count(<expr>), Sum(<expr>), Min(<expr>), Max(<expr>),
Partition   Top <expr>
Set         Distinct, Union, Intersect, Except
Order       Order By <expr>
Query Comprehensions
  Return _
    Select c.Name & “ works in ” & c.Country From c In Customers _
    Where c.Name.Length < 5

  Function _Filter1(c As Customer) As Boolean
    Return c.Name.Length < 5
  End Function

  Function _Project1(c As Customer) As Integer
    Return c.Name & “ works in ” & c.Country
  End Function

  Return _
    Sequence.Select( _
      Sequence.Where(Customers, AddressOf _Filter1), _
      AddressOf _Project1)
Extension Methods
 Behind the smoke and mirrors.
 Instance implementations given precedence over
 Static ones.
 Shared methods inside System.Query.Sequnece
 <Runtime.CompilerServices.Extension> _
 Shared Sub WriteToDebug(Of T)(collection As IEnumerable(Of T))
   For Each item As T in Collection
     Debug.Print item.ToString
 End Sub
Delayed Evaluation
 Results from a LINQ query are as
 IEnumerable(Of T)
 Also OrderedSequence(Of T), but think of it as
 IEnumerable(Of T)
 These are like cursors or stream readers.
 Evaluation does not occur until you iterate the
 Some extension methods, e.g Count iterate the
 Delayed evaluation means latest is always
 evaluated. Re-evaluated if iterated again.
 Use ToArray or ToList to get a “snapshot”
Object Initializers
  Class HitInfo
    Public Page As String
    Public Hits As integer
  End Class

  Dim hi As New HitInfo { Page, Hits := Sum(PageHits(Page)) }

  Dim hi As New HitInfo()

  With hi
    .Page = Page
    .Hits = Sum(PageHits(Page))
  End With
Anonymous types
 Dim result = Select c.Name, c.Address From c In Customers

 An anonymous type is defined for you with
 the properties Name and Address.
 Remember ObjectSpaces ?
 Specialised API for databases/SQL
 You can use standard LINQ queries (with
 some limitations)
 Relies heavily on declarative style
 programming  The use of attributes.
 Can be applied to your own business
 objects, or generate new ones using
DLINK classes & attributes
<Database(Name:=“DVDColleciton”)> _
Public Class MyDataBase
   Inherits DataContext

   Public DVDs As Table(Of DVD)
End Class

Public Class DVD

  <Column(Storage:=“m_Name”, Dbtype:=“NCHAR(255)” > _
    Public Property Name As String
    End Property

    Private m_Name AS String

End Class
 Manages change tracking
 Derive from and add your Table(Of t) to it
 Can create a database for you
 Provides easy ways to work with .mdf files
 Translates expression trees to TSQL
Change tracking
 Default change tracking is done by
 comparing a copy held in memory
 Better to Implement IChangeNotifier
   Public Event ObjectChanging as Object ChangingEventHandler

 Need to raise the event where appropriate
 in the your property Sets
 SQLMetal generates this kind of code for
 you 
 Object model, not tables, so Customers can
 have an orders Property.
 Specify the relationship via the Association
 Loading can be delayed
 To load as part of the query, add the Including
 statement to the query, e.g:
  Including c.Orders
 Storage must be an EntityRef(Of t) for one to one
 (eg Order to Customer), and an EntitySet(Of T)
 for one to many (eg Customer To Order)
 SQLMetal generates this kind of code for you 
XLinq Class Hierarchy

     XName      XAttribute     XNode

XCData    XComment XContainer XDocumentType XDeclaration

No Text
             XDocument       XElement
XLinq In-Memory XML API
The power of DOM in a modern, redesigned API

Key Design Points:       Document context not required

  Document “Free”                  public XElement(XName name,
                                       params object[] content);
  Functional Construction
  Working with Text
  Smaller, Faster        (string) customer.Element(“LastName”);

  XML Name Simplification
XLinq in VB 9.0
 XML Literals
   Easier Functional construction
   Embedded Expression Holes (<%= =>)
 Late Bound XML
   . (Elements)
   … (Descendants )
   .@ (Attribute)
XML Literals
 Shorthand for object creation
  Dim emp = _
      <department id="432">

  Dim emp = _
    New XElement("employee", _
      New XElement("name", "Joe"), _
      New XElement("age", 28), _
      New XElement("department", _
        New XElement("name", "Engineering"), _
        New XAttribute("id", 432)))
Extensible Late Binding
 Late binding covers all XML axes
  Dim cosmos As XElement = GetCurrentLinkCosmos().Root
  Dim ver As Double = CDbl(cosmos.Attribute("version"))
  Dim item As XElement = First(cosmos.Descendents("item"))
  Dim created As Date = CDate(item.Element("linkcreated“))
  Dim cosmos As XElement = GetCurrentLinkCosmos().Root
  Dim ver As Double = CDbl(cosmos.@version)
  Dim item As XElement = First(cosmos…item)
  Dim created As Date = CDate(item.linkcreated)
Dynamic Interfaces
  Impose structure on late-bound objects
                              Have to cast!

                 Cosmos = GetCurrentLinkCosmos().Root No
 Dim cosmos As XElement = GetCurrentLinkCosmos().Root
 Dim ver As Double = CDbl(cosmos.@version)
                      cosmos.@version            Intellisense!
             Item = First(cosmos…item)
 Dim item As XElement = First(cosmos…item)
 Dim created As Date = CDate(item.linkcreated)

 Dynamic Interface Item
                              Defines the
   Property Created() As Date late-bound
 End Interface                   shape

 Dynamic Interface Cosmos
   <Axis(Attribute)> Property Version() As Double
   <Axis(Descendent)> Public Property Item() As Integer
 End Interface
Further Reading /Downloads

 My Contact Details
   Nick Randolph

To top