Can I use foreach to return only a certain type from a collection?

Posted by RoboShop on Stack Overflow See other posts from Stack Overflow or by RoboShop
Published on 2010-05-04T07:18:19Z Indexed on 2010/05/04 7:28 UTC
Read the original article Hit count: 255

Filed under:
|
|

If I enter the code below, I get an error. Basically, the foreach will break when it comes across a Control that isn't a label.

foreach (Label currControl in this.Controls()) {

...
}

I have to do something like this.

foreach (Control currControl in this.Controls()) {
    if(typeof(Label).Equals(currControl.GetType())){

    ...
    }

}

can anyone think of a better way of doing it without me needing to check the type? Can I somehow get foreach to skip the objects that aren't Labels?

© Stack Overflow or respective owner

Related posts about c#

Related posts about foreach