Doing Visual Basic LINQ

Introduction

Every day, technology becomes smarter and things get done quicker. LINQ has been around for some time and I am surprised that I only cover LINQ now. Today, I will show you how to use LINQ productively with Visual Basic.

LINQ

Language-Integrated Query (LINQ) adds query capabilities to Visual Basic. LINQ uses a unified syntax irrespective of the type of data. Instead of sending a query to a database, or working with different query syntax for different types of data that are being searched, LINQ provides queries as part of the Visual Basic language.

For more detailed information regarding LINQ, please have a look at the following articles:

Our Project

Open Visual Studio and create a new Visual Basic Windows Forms project. Design your form to resemble Figure 1.

LINQ

Figure 1: Our design

Add two classes to your project. Name one Student and the other Course. Then, create the following fields for each.

Student

Public Class Student
   Public Property StudentID As Integer
   Public Property StudentName As String
   Public Property CourseID As Integer
   Public Property StudentAge As Integer
End Class

Course

Public Class Course
   Public Property CourseID As Integer
   Public Property CourseName As String
   Public Property CourseDuration As Integer
End Class

Now, we have a Student class and a Course class. These classes represent our data sources at the end of the day and will be used in our LINQ queries to insert and extract information.

Create the following two functions in your Form:

   Private Function GetStudents() As List(Of Student)
      Return New List(Of Student) From
      {
         New Student With {.StudentID = 1, .StudentName = "Hannes du Preez", _
            .CourseID = 3, .StudentAge = 38},
         New Student With {.StudentID = 2, .StudentName = "Elmarie du Preez", _
            .CourseID = 1, .StudentAge = 38},
         New Student With {.StudentID = 3, .StudentName = "Michaela du Preez", _
            .CourseID = 2, .StudentAge = 16}
      }
   End Function
   Private Function GetCourses() As List(Of Course)
      Return New List(Of Course) From
         {
            New Course With {.CourseID = 1, .CourseName = "Programming", _
               .CourseDuration = 5},
            New Course With {.CourseID = 2, .CourseName = "Introduction to PCs", _
               .CourseDuration = 12},
            New Course With {.CourseID = 3, .CourseName = "Graphic Design", _
               .CourseDuration = 4}
         }
   End Function

With the preceding functions, I simply populate the respective class’ properties with some data, thus creating student objects and Course objects. You may notice that there is one common key in both classes. This field is CourseID and links the Student object to the Course object. A bit later, you will see how you can create a query that combines data from both classes, but let me not get too ahead of myself here (as usual) and start with the basics…

A Basic LINQ Query

Add the following code behind the buttons labeled ‘Get Students‘ and ‘Get Courses‘:

   Private Sub Button1_Click(sender As Object, e As EventArgs) _
         Handles Button1.Click
      Dim students = GetStudents()
      Dim queryResults = From stu In students
      For Each result In queryResults
         Debug.WriteLine(result.StudentID.ToString() & " " & result.StudentName & _
            " " & result.StudentAge.ToString() & " " & result.CourseID.ToString())
      Next
   End Sub
   Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      Dim courses = GetCourses()
      Dim queryResults = From cour In courses
      For Each result In queryResults
         Debug.WriteLine(result.CourseID.ToString() & " " & result.CourseName & _
            " " & result.CourseDuration.ToString())
      Next
   End Sub

A new Student and Course object get created with the help of the GetStudents and GetCourses functions. The For Each loop loops through each of the student and course objects present in the Student and Course objects, then display the results one by one. This is the most basic form of a LINQ query. Let’s get more complicated now. Add the next code behind the button labeled ‘WHERE‘:

   Private Sub Button3_Click(sender As Object, e As EventArgs) _
         Handles Button3.Click
      Dim students = GetStudents()
      Dim queryResults = From stu In students
         Where stu.CourseID = 3
      For Each result In queryResults
         Debug.WriteLine(result.StudentID.ToString() & " " _
            & result.StudentName & " " & result.StudentAge.ToString() & " " _
            & result.CourseID.ToString())
      Next
   End Sub

With the help of the WHERE statement, here we can filter the query object’s results to display only specific data. For the uninformed, this WHERE statement serves the exact same purpose as the WHERE statement present in any SQL query. If you do not have an SQL background, please refer to this article.

Add the following code behind the button labeled ‘SELECT‘:

   Private Sub Button4_Click(sender As Object, e As EventArgs) _
         Handles Button4.Click
      Dim courses = GetCourses()
      Dim queryResults = From cour In courses
         Where cour.CourseID = 3
            Select cour.CourseName, cour.CourseDuration
      For Each result In queryResults
         Debug.WriteLine(result.CourseName & " " _
            & result.CourseDuration.ToString())
      Next
   End Sub

This LINQ Query allows you to specify the fields you’d like to return. Instead of returning all the fields present in the Course object, I have returned only data from the CourseName field and the CourseDuration field. Add the following code behind the button labeled ‘COMBINE FROM‘:

   Private Sub Button5_Click(sender As Object, e As EventArgs) _
         Handles Button5.Click
      Dim students = GetStudents()
      Dim courses = GetCourses()
      Dim queryResults = From stu In students, cour In courses
         Where stu.CourseID = cour.CourseID
         Select stu, cour
      For Each result In queryResults
         Debug.WriteLine(result.stu.StudentName & " " _
            & result.cour.CourseName)
      Next
   End Sub

This LINQ query returns data from both the Student and Course objects.

Conclusion

Obviously, this is only the tip of the iceberg. LINQ can become your best friend very quickly once you know the basics.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read