Is it possible to use foreach to return only a specific type from a collection?

If I enter the code below, I get an error. Basically, foreach will break when it encounters a control that is not a label.

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

...
}

I need to do something like this.

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

    ...
    }

}

can anyone think of a better way to do this without me to check the type? Can I somehow make foreach skip objects that are not shortcuts?

+5
source share
2 answers

If you are using .NET 3.5 or later, you can do something like this

foreach(var label in this.Controls().OfType<Label>()) {
}

OfType<T> , T. . http://msdn.microsoft.com/en-us/library/bb360913.aspx

+10

OfType. , , , . :

if(typeof(Label).Equals(currControl.GetType())){

...
}

:

if (currControl is Label)
{
    Label label = (Label) currControl;
    // ...
}

Label label = currControl as Label;
if (label != null)
{
    // ...
}

, Label, .

+6

All Articles