如果我想在ASP.NET页面上找到选中的复选框,我可以使用以下LINQ查询。
var checkBoxes = this.Controls .OfType<CheckBox>() .TakeWhile<CheckBox>(cb => cb.Checked);
这很好,如果复选框嵌套在当前控件集合,但我想知道如何通过深入到顶层控件的控件集合中扩展搜索。
这里问的问题:
Finding controls that use a certain interface in ASP.NET
并且收到非LINQ的答案,我已经有我自己的版本的递归控制搜索类型和ID作为扩展方法,但我只是想知道这是多么容易这是做LINQ?
解决方法
从递归中获取类型/ ID检查,所以只需要“给我所有的控件,递归”方法,例如。
public static IEnumerable<Control> GetAllControls(this Control parent) { foreach (Control control in parent.Controls) { yield return control; foreach(Control descendant in control.GetAllControls()) { yield return descendant; } } }
这是有点低效率(在创建大量的迭代器方面),但我怀疑你会有一个非常深的树。
然后,您可以将原始查询写为:
var checkBoxes = this.GetAllControls() .OfType<CheckBox>() .TakeWhile<CheckBox>(cb => cb.Checked);
(编辑:将AllControls更改为GetAllControls,并将其正确地用作方法。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。