c# - 如何在 ItemCollection 中找到具有特定属性的项目?
问题描述
我有一个带有不同类型 UserControls 的 ItemsCollection,需要查找是否有任何对象满足条件Any(p => p.GotFocus)
。由于 ItemsCollection 没有实现 IEnumerable,因此我可以将集合转换为某种类型,如ItemCollection 的基本 LINQ 表达式中所述:
bool gotFocus = paragraphsItemControl.Items.Cast<ParagraphUserControl>().Any(p => p.GotFocus);
该集合由不同类型的 UserControls 组成(虽然每个都继承自同一个父级),所以如果我强制转换为特定类型,则会引发异常。如何查询 UserControl 对象的集合?
解决方案
使用OfType()
而不是Cast()
:
bool gotFocus = paragraphsItemControl.Items
.OfType<ParagraphUserControl>().Any(p => p.GotFocus);
但请注意,这只会ParagraphUserControl
检查类型的控件。
假设所有控件都继承自Parent
并Parent
具有GotFocus
属性,然后检查所有控件,您可以这样做:
bool gotFocus = paragraphsItemControl.Items
.Cast<Parent>().Any(p => p.GotFocus);
推荐阅读
- selenium-webdriver - 针对 Safari 运行量角器测试时出现 WebDriverError
- java - 根据数据库中的要求显示链接和页面访问
- java - wait(), notify() - 用于快速读取文件
- python-3.x - PyTorch CUDA 与 Numpy 的算术运算?最快的?
- android - Android Studio 中的两个错误
- regex - 微调正则表达式
- reactjs - Material UI:底部导航与 iOS 上的 Progressive Web App (PWA) Safari 对齐
- php - 多个主机的 wamp vhosts 问题
- r - 使用 group_by 时创建汇总值并汇总
- python - 使用网状将R变量传递给python脚本