Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net: Iterating over multiple repeater.items collections

I have a number of idential repeaters, and I need to iterate through all of the items. I currently have:

 For Each item In rpt1.Items
    ...do some stuff
 Next

 For Each item In rpt2.Items
    ...exact same code
 Next

Is there a simple way to reduce this to a single For Each ... Next loop?

Edit: There are a number of local vars involved in "do some stuff", which is why I can't just pass the item into a function - the call would have to include about 8 ByRef params.

like image 485
chris Avatar asked Apr 01 '11 11:04

chris


1 Answers

Simply put your code into a separate method:

For Each item In rpt1.Items
    DoSomethingWith(item)
Next
For Each item In rpt2.Items
    DoSomethingWith(item)
Next 

...

Sub DoSomethingWith(item As RepeaterItem)
   ... put your common code here ...
End Sub

EDIT: If you have lots of local variables, using a local lambda might be an option:

Dim doSomething = Sub(item As RepeaterItem)
                      ... do some stuff using all available local variables
                  End Sub

For Each item In rpt1.Items
    doSomething(item)
Next
For Each item In rpt2.Items
    doSomething(item)
Next 

EDIT: One more option, which does not require lambdas:

For Each rpt In New Repeater() {rpt1, rpt2}
    For Each item In rpt.Items
        ...do something with item and rpt
   Next
Next
like image 115
Heinzi Avatar answered Oct 04 '22 01:10

Heinzi