开发者

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.


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


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>()))
{
}


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   
                }
            }
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜