Add Elegance to Lists Object in VB.NET

It is a fairly common programming scenario to find ourselves with a list of identical objects. In the past, without adequate support from programming languages, we found ourselves writing a lot of searching and sorting code, and that may have put you off using lists in favour of arrays. All that has changed with VB.Net - its implementation of a list makes handling such lists remarkably easy.

For example, given the following class Person:

Public Class Person

  Public age As Integer

  Public name As String  Public Sub New(age As Integer, name As String)

    Me.age = age

    Me.name = name

  End Sub

End Class


We can create a list of Person objects and add six people like so:


Dim people As New List(Of Person)()


people.Add(New Person(50, "Fred"))

people.Add(New Person(30, "John"))

people.Add(New Person(26, "Andrew"))

people.Add(New Person(24, "Xavier"))

people.Add(New Person(5, "Mark"))

people.Add(New Person(6, "Cameron"))


We can access the data in the list using LINQ.   The following code demonstrates how we might work with our person list:

Dim unsorted = From p In people Select p

Dim sortedByAge = From p In people Order By p.age Select p

Dim theYoung = From p In people Where p.age < 25 Select p

Dim sortedByName = From p In people Order By p.name Select p

Console.WriteLine("Unsorted list")

For Each p1 As Person In unsorted

       Console.WriteLine(String.Format("{0} {1}", p1.name, p1.age))

Next


Console.WriteLine("Age is less than 25")

For Each p1 As Person In theYoung

       Console.WriteLine(String.Format("{0} {1}", p1.name, p1.age))

Next

 

Console.WriteLine("Sorted list, by name")

For Each p1 As Person In sortedByName

      Console.WriteLine(String.Format("{0} {1}", p1.name, p1.age))

Next


Console.WriteLine("Sorted list, by age")

For Each p1 As Person In sortedByAge

     Console.WriteLine(String.Format("{0} {1}", p1.name, p1.age))

Next


And here is the output that we should expect:

Unsorted list
50 Fred
30 John
26 Andrew
24 Xavier
5 Mark
6 Cameron

Age is less than 25
24 Xavier
5 Mark
6 Cameron

Sorted list, by name
26 Andrew
6 Cameron
50 Fred
30 John
5 Mark
24 Xavier

Sorted list, by age
5 Mark
6 Cameron
24 Xavier
26 Andrew
30 John
50 Fred

Lists are powerful and result in fewer, and more elegant, lines of code. Hopefully this short example has demonstrated their ease and you will find yourself using them in your day-to-day development activities.


Similar Articles