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 ofCast():But please note that this only controls of type
ParagraphUserControlwill be checked.Assuming that all of the controls inherited from
ParentandParenthasGotFocusproperty then to check all controls you can do this: