Results 1 to 3 of 3

Thread: Unknown number of nested loops

  1. #1

    Thread Starter
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Angry Unknown number of nested loops

    Hello, I've got a problem I've been banging my head upon for three days by now.
    I'll try to put it as simply as I can. Basically, I've got a list of lists, for example like this:

    1. KPP1, KPP2
    2. VAP1, VAP2, VAP3
    3. T1, T2


    What i need is to iterate through this list and build a list like this:
    KPP1-VAP1-T1
    KPP1-VAP1-T2
    KPP1-VAP2-T1
    KPP1-VAP2-T2
    KPP1-VAP3-T1
    KPP1-VAP3-T2
    KPP2-VAP1-T1
    KPP2-VAP1-T2
    KPP2-VAP2-T1
    KPP2-VAP2-T2
    KPP2-VAP3-T1
    KPP2-VAP3-T2

    Normally it woudln't be a problem, but to me the number of 'levels' in this is unknown and can be any, for example as simple as this:
    1. KPP1

    or like this
    1. KPP1, KPP2, KPP3
    2. VAP1, VAP2
    3. T1, T2, T3, T4, T5
    4. X1, X2, X3, X4

    Since I don't know how many levels and how many elements at each level there is I cannot simply make a necessary number of nested loops - I've got to think of something different. Any ideas?

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,222

    Re: Unknown number of nested loops

    This sounds like a job for... dun dah dah duuun... recursion.
    Code:
    Private Sub DisplayItems(list As IEnumerable)
        For Each item In list
            Dim sublist = TryCast(item, IEnumerable)
    
            If sublist Is Nothing Then
                MessageBox.Show(item.ToString())
            Else
                DisplayItems(sublist)
            End If
        Next
    End Sub
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width