I have an ItemsCollection with UserControls of different types, and need to find if any object satisfies the condition Any(p => p.GotFocus)
. As the ItemsCollection does not implement IEnumerable, I could cast the collection to a certain type, as explained in Basic LINQ expression for an ItemCollection like this:
bool gotFocus = paragraphsItemControl.Items.Cast<ParagraphUserControl>().Any(p => p.GotFocus);
The collection consists of different types of UserControls (each inherits from the same parent though), so an exception is thrown if I cast to a specific type. How can I query the collection of UserControl objects?
use OfType()
instead of Cast()
:
bool gotFocus = paragraphsItemControl.Items
.OfType<ParagraphUserControl>().Any(p => p.GotFocus);
But please note that this only controls of type ParagraphUserControl
will be checked.
Assuming that all of the controls inherited from Parent
and Parent
has GotFocus
property then to check all controls you can do this:
bool gotFocus = paragraphsItemControl.Items
.Cast<Parent>().Any(p => p.GotFocus);