chris
chris

Reputation: 37450

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.

Upvotes: 7

Views: 3261

Answers (3)

Heinzi
Heinzi

Reputation: 172220

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

Upvotes: 4

user1921
user1921

Reputation:

This is C#, but it will check all the controls and child controls for repeater controls and then do whatever you needed it to do.

Call it like this:

DoSomethingWithMyRepeaterControls(Form.Controls);

The method:

private static void DoSomethingWithMyRepeaterControls(ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                if(control.HasControls())
                    DoSomethingWithMyRepeaterControls(control.Controls);

                if(control.GetType() == typeof(Repeater))
                {
                    //here there be tygers   
                }
            }
        }

Upvotes: 1

Hawxby
Hawxby

Reputation: 2804

In C# I'd do something like this in LINQ, not sure if you can convert that to VB.

var rep1 = new Repeater();
var rep2 = new Repeater();
var rep3 = new Repeater();

foreach (var item in rep1.Items.OfType<ListItem>()
    .Concat(rep2.Items.OfType<ListItem>())
    .Concat(rep3.Items.OfType<ListItem>()))
{
}

Upvotes: 1

Related Questions