Home

Introduction to the LINQ

   

The Language Integrated Query

 

Introduction

 

The Language Integrated Query, abbreviated LINQ, is a technology used to create a sub-list based on an existing list. The new list could be the same as the original, it could be a list of selected values from the original, or it can be a different arrangement of the values of the first list.

   

Practical Learning: Introducing LINQ

  1. Start Microsoft Visual Studio or Microsoft Visual Basic 2010 Express
  2. Create a Console Application named AltairRealtors1
  3. To create a new class, in the Class View, right-click AltairRealtors1 -> Add -> Class...
  4. Change the name to House and press Enter
  5. Complete the class as follows:
    Public Enum PropertyType
        Condominium
        Townhouse
        SingleFamily
        Unknown
    End Enum
    
    Public Enum PropertyCondition
        Unknown
        Excellent
        Good
        NeedsRepair
        BadShape
    End Enum
    
    <Serializable()>
    Public Class House
        Private nbr As Integer
        Private tp As PropertyType
        Private ct As String
        Private stt As String
        Private cond As PropertyCondition
        Private beds As Short
        Private baths As Single
        Private levels As Integer
        Private yr As Integer
        Private val As Decimal
    
        Public Sub New()
            nbr = 0
            tp = PropertyType.Unknown
            ct = "Unknown"
            stt = "AA"
            cond = PropertyCondition.Unknown
            beds = 0
            baths = 0.0
            levels = 0
            yr = 1900
            val = 0
        End Sub
    
        Public Sub New(ByVal propNbr As Integer, ByVal type As PropertyType,
                       ByVal city As String, ByVal state As String,
                       ByVal condition As PropertyCondition, ByVal bedrooms As Short,
                       ByVal bathrooms As Single, ByVal stories As Integer,
                       ByVal year As Integer, ByVal value As Decimal)
            nbr = propNbr
            tp = type
            ct = city
            stt = state
            cond = condition
            beds = bedrooms
            baths = bathrooms
            levels = stories
            yr = year
            val = value
        End Sub
    
        Public Property PropertyNumber As Integer
            Get
                Return nbr
            End Get
            Set(ByVal value As Integer)
                nbr = value
            End Set
        End Property
    
        Public Property Type As PropertyType
            Get
                Return tp
            End Get
            Set(ByVal value As PropertyType)
                tp = value
            End Set
        End Property
    
        Public Property City As String
            Get
                Return ct
            End Get
            Set(ByVal value As String)
                ct = value
            End Set
        End Property
    
        Public Property State As String
            Get
                Return stt
            End Get
            Set(ByVal value As String)
                stt = value
            End Set
        End Property
    
        Public Property Condition As PropertyCondition
            Get
                Return cond
            End Get
            Set(ByVal value As PropertyCondition)
                cond = value
            End Set
        End Property
    
        Public Property Bedrooms As Short
            Get
                If beds <= 1 Then
                    Return 1
                Else
                    Return beds
                End If
            End Get
                set (value as short)
                beds = value
            End Set
        End Property
    
            public property Bathrooms as single
            Get
                If baths <= 0 Then
                    Return 0
                Else
                    Return baths
                End If
            End Get
            Set(ByVal value As Single)
                baths = value
            End Set
        End Property
    
        Public Property Stories As Integer
            Get
                Return levels
            End Get
            Set(ByVal value As Integer)
                levels = value
            End Set
        End Property
    
        Public Property YearBuilt As Integer
            Get
                Return yr
            End Get
            Set(ByVal value As Integer)
                yr = value
            End Set
        End Property
    
        Public Property MarketValue As Decimal
            Get
                If val <= 0 Then
                    Return 0
                Else
                    Return val
                End If
            End Get
            Set(ByVal value As Decimal)
                val = value
            End Set
        End Property
    End Class
  6. In the Solution Explorer, right-click Module1.vb and click Rename
  7. Type AltairRealtors.vb and press Enter twice to display the file
  8. Change the file as follows:
    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    
    Module AltairRealtors
    
        Function Main() As Integer
    
            Dim lstProperties(19) As House
    
            lstProperties(0) = New House(524880, PropertyType.SingleFamily, "Silver Spring", "MD",
                            PropertyCondition.Good, 4, 2.5F, 3, 1995, 495880.0)
            lstProperties(1) = New House(688364, PropertyType.SingleFamily, "Alexandria", "VA",
                            PropertyCondition.Excellent, 4, 3.5F, 2, 2000, 620724.0)
            lstProperties(2) = New House(611464, PropertyType.SingleFamily, "Laurel", "MD",
                            PropertyCondition.Good, 0, 0.0F, 2, 0, 422625.0)
            lstProperties(3) = New House(749562, PropertyType.Townhouse, "Gettysburg", "WV",
                            PropertyCondition.Good, 3, 2.5F, 3, 2002, 425400.0)
            lstProperties(4) = New House(420115, PropertyType.Unknown, "Washington", "DC",
                            PropertyCondition.Unknown, 2, 0.0F, 0, 1982, 312555.0)
            lstProperties(5) = New House(200417, PropertyType.Condominium, "Germantown", "MD",
                            PropertyCondition.Excellent, 2, 1.0F, 0, 0, 215495.0)
            lstProperties(6) = New House(927474, PropertyType.Townhouse, "Arlington", "VA",
                            PropertyCondition.BadShape, 4, 2.5F, 3, 1992, 415665.0)
            lstProperties(7) = New House(682630, PropertyType.SingleFamily, "Martinsburg", "WV",
                            PropertyCondition.Good, 4, 3.5F, 3, 2005, 325000.0)
            lstProperties(8) = New House(288540, PropertyType.Condominium, "Silver Spring", "MD",
                            PropertyCondition.Good, 1, 1.0F, 0, 2000, 242775.0)
            lstProperties(9) = New House(247472, PropertyType.SingleFamily, "Silver Spring", "MD",
                            PropertyCondition.Excellent, 3, 3.0F, 3, 1996, 625450.0)
            lstProperties(10) = New House(297446, PropertyType.Townhouse, "Laurel", "MD",
                            PropertyCondition.Unknown, 4, 1.5F, 2, 2002, 412885.0)
            lstProperties(11) = New House(924792, PropertyType.SingleFamily, "Washington", "DC",
                            PropertyCondition.Good, 5, 3.5F, 3, 2000, 555885.0)
            lstProperties(12) = New House(294796, PropertyType.SingleFamily, "Falls Church", "VA",
                            PropertyCondition.Excellent, 5, 2.5F, 2, 1995, 485995.0)
            lstProperties(13) = New House(811155, PropertyType.Condominium, "Alexandria", "VA",
                            PropertyCondition.Good, 1, 1.0F, 0, 2000, 352775.0)
            lstProperties(14) = New House(447597, PropertyType.Townhouse, "Hyattsville", "MD",
                            PropertyCondition.Excellent, 3, 2.0F, 3, 1992, 365880.0)
            lstProperties(15) = New House(297415, PropertyType.Townhouse, "ashington", "DC",
                            PropertyCondition.Good, 4, 3.5F, 1, 2004, 735475.0)
            lstProperties(16) = New House(475974, PropertyType.SingleFamily, "Gaithersburg", "MD",
                            PropertyCondition.Unknown, 4, 2.5F, 1, 1965, 615775.0)
            lstProperties(17) = New House(927409, PropertyType.Condominium, "McLean", "VA",
                            PropertyCondition.Excellent, 1, 1.0F, 12, 2006, 485900.0)
            lstProperties(18) = New House(304750, PropertyType.Condominium, "Washington", "DC",
                            PropertyCondition.Unknown, 2, 2.0F, 6, 1992, 388665.0)
            lstProperties(19) = New House(207850, PropertyType.Townhouse, "Rockville", "MD",
                            PropertyCondition.Good, 3, 2.5F, 2, 1988, 525995.0)
    
            Dim stmProperties As FileStream = Nothing
            Dim bfmProperties As BinaryFormatter = New BinaryFormatter
    
            ' If this directory doesn't exist, create it
            Directory.CreateDirectory("C:\Altair Realtors")
            ' This is the file that holds the list of properties
            Dim Filename As String = "C:\Altair Realtors\Properties.atr"
    
            ' Find out if there is already a file that contains a list of properties.
            ' If that file exists, open it to get it ready for the new properties.
            If File.Exists(Filename) Then
                stmProperties = New FileStream(Filename,
                                               FileMode.Open,
                                               FileAccess.Read,
                                               FileShare.Read)
    
                Try
                    ' Retrieve the list of items from file
                    lstProperties = CType(bfmProperties.Deserialize(stmProperties), House())
                Finally
                    stmProperties.Close()
                End Try
            End If
    
            ' Save the list of properties
            stmProperties = New FileStream(Filename,
                                          FileMode.Create,
                                          FileAccess.Write,
                                          FileShare.Write)
    
            Try
                bfmProperties.Serialize(stmProperties, lstProperties)
            Finally
                stmProperties.Close()
            End Try
    
            Return 0
        End Function
    
    End Module
  9. Execute the application to create the list
  10. Close the DOS window and return to your programming environment
  11. Change the file as follows:
    Imports System.IO
    Imports System.Runtime.Serialization.Formatters.Binary
    
    Module AltairRealtors
        Private lstProperties() As House
    
        Function Main() As Integer
    
            Dim stmProperties As FileStream = Nothing
            Dim bfmProperties As BinaryFormatter = New BinaryFormatter
    
            ' This is the file that holds the list of properties
            Dim Filename As String = "C:\Altair Realtors\Properties.atr"
    
            ' Find out if there is already a file that contains a list of properties.
            ' If that file exists, open it.
            If File.Exists(Filename) Then
                stmProperties = New FileStream(Filename,
                                              FileMode.Open,
                                              FileAccess.Read,
                                              FileShare.Read)
    
                Try
                    ' Retrieve the list of items from file
                    lstProperties = CType(bfmProperties.Deserialize(stmProperties), House())
                Finally
                    stmProperties.Close()
                End Try
            End If
    
            Return 0
        End Function
    
    End Module
 
 
 

Querying a List

To use LINQ in your application, you must include the System.Core.dll assembly in your program. If you started your application as an empty project:

  • On the main menu, you can click Project -> Add Reference...
  • In the Solution Explorer, you can right-click the name of the project and click Add Reference...
  • In the Class View, you can right-click the name of the project and click Add Reference...

In the .NET tab of the Add Reference dialog box, you can click System.Core

Add Reference

Click OK. You must then use the System.Linq namespace in your code or you can import it.

Creating a Query

To query a list, you write a statement using words and operators of the LINQ. The most fundamental operation you can perform on LINQ consists of creating, also referred to as selecting, or querying, a list of values, from an existing list such as an array. The basic formula to use is:

Dim SubListName = From ValueHolder In List Select ValueHolder

The Dim keyword, the assignment operator "=", the From keyword, the In keyword, the Select keyword, and the semicolon are required.

The SubListName is a name of a new variable that will hold the list of values produced by this operation.

The ValueHolder is the name of a variable that will be used to identify each resulting member of this operation. This variable will be equivalent to getting each member of the list and that responds to a condition.

The List factor represents the name of the variable that you would have created already. The List can be an array. Here is an example:

Imports System.Linq

Module Exercise
    Public Function Main() As Integer
        Dim Numbers() = {12.44, 525.38, 6.28, 2448.32, 632.04}

        Dim Nbrs = From N In Numbers Select N

        For Each Member In Nbrs
            Console.WriteLine("Number: " & CStr(Member))
        Next

        Return 0
    End Function
End Module

This would produce:

Numbers

To make the code easier to read, you can spread the select statement to various lines. Here is an example:

Imports System.Linq

Module Exercise
    Public Function Main() As Integer
        Dim Numbers() = {12.44, 525.38, 6.28, 2448.32, 632.04}

        Dim Nbrs = From N
                   In Numbers
                   Select N

        For Each Member In Nbrs
            Console.WriteLine("Number: " & CStr(Member))
        Next

        Return 0
    End Function
End Module
 
 
   
 

Home Copyright © 2010 FunctionX, Inc. Next