The Edge

Web application development insights written for our team, but open to the development community.

Simplifying creating a list in vb.net

Published on August 20, 2010

Often we need to create a list of arbitrary items in vb.net.

A common scenario when working with MVC is creating SelectListItems for use in a drop down list.

We would often create code like the this;

        Dim deductions As New List(Of Mvc.SelectListItem)
        deductions.Add(New SelectListItem() With {.Text = "PAYG", .Value = "PAYG"})
        deductions.Add(New SelectListItem() With {.Text = "GST", .Value = "GST"})
        deductions.Add(New SelectListItem() With {.Text = "Superannuation", .Value = "Superannuation"})
        deductions.Add(New SelectListItem() With {.Text = "Savings", .Value = "Savings"})
        deductions.Add(New SelectListItem() With {.Text = "Child Support", .Value = "ChildSupport"})
        ViewData("deductionType") = deductions

This can be simplified by creating an array instead;

        ViewData("deductionType") = {
                New SelectListItem() With {.Text = "PAYG", .Value = "PAYG"},
                New SelectListItem() With {.Text = "GST", .Value = "GST"},
                New SelectListItem() With {.Text = "Superannuation", .Value = "Superannuation"},
                New SelectListItem() With {.Text = "Savings", .Value = "Savings"},
                New SelectListItem() With {.Text = "Child Support", .Value = "ChildSupport"}
        }

Note that in vb.net 10.0 we don’t need to add the _ at the end of lines that obviously continue on the next line, such as these.

An array will work for most scenarios, but if it is indeed a list we are after, then we can create a list by adding .ToList() to the end, like so;

        ViewData("deductionType") = {
                New SelectListItem() With {.Text = "PAYG", .Value = "PAYG"},
                New SelectListItem() With {.Text = "GST", .Value = "GST"},
                New SelectListItem() With {.Text = "Superannuation", .Value = "Superannuation"},
                New SelectListItem() With {.Text = "Savings", .Value = "Savings"},
                New SelectListItem() With {.Text = "Child Support", .Value = "ChildSupport"}
        }.ToList()

Filed under: vb.net
Tags: ,

Leave a Reply