Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

The following code builds an ASP.NET menu recursively from data in a database:

Imports Microsoft.VisualBasic

Public Class MenuBarHelper

    Public Shared Function GetMainMenu() As Menu

        Dim menuItem As New MenuItem

        BuildMainMenu(menuItem, 1)

        Dim menu As New Menu

        While menuItem.ChildItems.Count > 0
            menu.Items.Add(menuItem.ChildItems(0))
        End While

        If menu.Items.Count < 1 Then Return Nothing

        Return menu

    End Function

    Private Shared Sub BuildMainMenu(menuItem As MenuItem, pageId As Integer)

        Dim dc As New AutomationDataContext

        Dim pages = From r In dc.PageOnlineOnlies Where r.ParentId = pageId Order By r.Weight Descending, r.Id Ascending Select r

        For Each page In pages

            Dim a As HtmlAnchor = HtmlHelper.GetHtmlAnchor(page.MenuItemHtmlAnchor)

            If a Is Nothing Then Continue For

            Dim mi As New MenuItem With {.Text = a.InnerText, .NavigateUrl = a.HRef, .ToolTip = a.Title}

            menuItem.ChildItems.Add(mi)

            pageId = page.Id

            BuildMainMenu(mi, pageId)

        Next

    End Sub

End Class

Please can someone help me reduce the lines of code and make this more elegant?

  • Is it possible to eliminate the for loop?
  • How can I restructure it so that I don't need a while loop?
  • The first MenuItem is only used to store child menu items and is a bit of a hack...

Many thanks.

P.S. I am developing an ASP.NET (VB.NET) web-forms website retrieving data from a SQL Server 2008 R2 database running on IIS7 on Windows Server 2008.

share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.