【发布时间】:2020-07-24 21:43:37
【问题描述】:
Linq 总是让我感到困惑。我正在尝试从控件 ID 包含特定字符串的 ASP.Net 表单页面中提取所有控件。控件集合是分层的,我想从所有级别返回任何匹配的控件。我在球场的任何地方吗?我真的可以使用一些帮助/教育。 collection 参数是页面中控件的集合,controlID 是我要搜索的文本。
public static Control FindControlsByControlID(ControlCollection collection, string controlID)
{
IEnumerable<Control> controls = collection.Cast<Control>();
IEnumerable<Control> matchedControls = controls
.SelectMany(p => p.Controls.Cast<Control>()
.SelectMany(c => c.Controls.Cast<Control>())
.Where(d => d != null ? d.ID != null ? d.ID.Contains(controlID) : false : false))
.Where(a => a != null ? a.ID != null ? a.ID.Contains(controlID) : false : false);
ConcurrentQueue<Control> cq;
if (matchedControls != null)
cq = new ConcurrentQueue<Control>(matchedControls);
else
return null;
...
提前致谢!
【问题讨论】:
-
你所拥有的应该可以工作,但不需要在每个
SelectMany级别进行测试,只需在最后进行测试。另外,请使用&&而不是?:。但你只会深入两层。 -
Forms有Names,而不是IDs?这段代码真的可以编译吗?
标签: linq ienumerable controlcollection