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.