Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 908
Diskdrive Avatar asked May 04 '10 07:05

Diskdrive


People also ask

Does foreach call Dispose?

Yes, foreach will call Dispose() on the enumerator if it implements IDisposable.

Does foreach create a copy?

forEach() does not make a copy of the array before iterating.

How does foreach work in C#?

How Does It Work? The foreach loop in C# uses the 'in' keyword to iterate over the iterable item. The in keyword selects an item from the collection for the iteration and stores it in a variable called the loop variable, and the value of the loop variable changes in every iteration.


2 Answers

If you're on .NET 3.5 or newer, you can do something like this

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

OfType<T> will ignore types that cannot be cast to T. See http://msdn.microsoft.com/en-us/library/bb360913.aspx

like image 160
Brian Rasmussen Avatar answered Sep 22 '22 11:09

Brian Rasmussen


Brian has given the most appropriate answer in terms of OfType. However, I wanted to point out that there's a better way of checking for types in cases where you do need to do it. Instead of your current code:

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

...
}

You can use:

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

or:

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

Note that both of these alternatives will also include subclasses of Label, which your original code doesn't.

like image 39
Jon Skeet Avatar answered Sep 19 '22 11:09

Jon Skeet