Reader Level:
ARTICLE

Add Elegance to Lists Object in VB.NET

On November 09, 2012 Articles | Visual Basic .NET
A short and to-the-point tutorial that demonstrates how to sort and search using VB.Net's List object.
  • 0
  • 0
  • 18113

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.

Craig Murphy

Craig Murphy is employed by a leading professional services consulting firm as a Systems Development Engineer. Craig is also an author, developer, speaker, Microsoft Most Valuable Professional and Ce...

Personal Blog: http://www.craigmurphy.com
  • 477rank
  • 538K readers
COMMENT USING

Trending up