引用我在 filtering ('constraining') types in a foreach loop 上的问题,我正在尝试 Charlie Flowers 的回答中的第一种方法,在集合上使用 .Where 方法,但编译器无法在 System.Web.UI.ControlCollection 类上找到 .Where 。这是从 IEnumerable 派生的,所以这里有什么问题?
foreach (var control in Controls.Where(i => i.GetType() == typeof(TextBox)))
最佳答案
首先,确保您有 using System.Linq;
在文件的顶部。
如果您有一个实现了 IEnumerable
的集合但不是 IEnumerable<T>
,但您知道对象都是给定类型(例如 Control
),那么您可以使用 Cast<T>
LINQ扩展方法:
foreach (var control in Controls.Cast<Control>()
.Where(i => i.GetType() == typeof(TextBox))) {...}
但是,鉴于您的 Where
子句,在这种情况下,使用 OfType<T>
可能更为谨慎方法,它只返回给定类型的那些(Cast<T>
如果有任何错误则抛出异常):
foreach (var control in Controls.OfType<TextBox>()) {...}
这个版本和你的版本之间的细微差别是上面将返回 TextBox
的子类,哪里-作为你的GetType() == typeof(TextBox)
版本不会。
基本上,大多数 LINQ 扩展方法仅针对 IEnumerable<T>
定义。/IQueryable<T>
, 不是 IEnumerable
/IQueryable
.
关于c# - 'where()' 方法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/672612/