Erik Porter's Blog

Life and Development at Microsoft and Other Technology Discussions

News

    Reverse Loop Indexer

    This is a pretty specific case and pretty simple so I'm not sure anyone will get any use out of it (just simple math), but I thought it was interesting and would share (who knows, maybe I'll forget it and need to look it up again).

    In an application I'm working on right now, I store a list of parent items in a forward order.  When displaying calculations on child items of those parent items, I sometimes need to reverse their order inside the main parent loop (when printing them out).  For other purposes the child items are always in a forward order.  So basically what I needed was a way to, when looping through the parents backwards for display, get the opposite index of the loop from where I currently was to look up things in the children items.  This might seem confusing, so here's an example of what I wanted.

    Actual Loop Index Desired Loop Index
    0 4
    1 3
    2 2
    3 1
    4 0

    This ended up being really easy, but I had to think about it for a minute.

    Dim j As Integer
    Dim Count As Integer = 5

    For i As Integer = 0 To Count - 1
        
    j = Math.Abs(i - (Count - 1))
    Next

    This code would have the same values for i and j (respectively) as the above table.  Pretty simple, but handy.

    Comments

    dj said:

    don't use vb, but surely it will allow you to use a decrementing count in a for loop.
    # June 16, 2004 4:03 PM

    HumanCompiler said:

    Don't use VB? Why not? I use both VB and C# myself...sorry to hear you have a problem with VB ;) And yes, you can loop backwards in VB, but I wanted to loop forward (for other reasons) and just access the opposite loop index (as if i were going backwards) in the same loop.
    # June 16, 2004 4:07 PM

    Raj Kaimal said:


    Not sure why you are using the Math function.

    Dim j As Integer
    Dim Count As Integer = 5

    For i As Integer = 0 To Count - 1
    j = (Count - 1) - i
    Next
    # June 16, 2004 4:09 PM

    HumanCompiler said:

    Because I overcomplicate things sometimes...thanks, Raj ;)
    # June 16, 2004 4:12 PM

    Jason Nussbaum said:

    I'm assuming you can't do this in VB, but I know it's valid in JavaScript/ActionScript and believe it's valid in C#:
    [as/js]
    var Count:Number = 5;
    for( var i:Number=0,j:Number=Count-1; i < Count; i++,j-- )
    {
    // process
    trace( i + " :: " + j );
    }

    Is there no simple way to do that in VB?
    eg:
    For i As Integer = 0 To Count - 1, j As Integer = Count - 1 to 0
    ' process
    Next
    # June 17, 2004 2:43 PM