【问题标题】:Linq cannot filter elements in loopLinq 无法过滤循环中的元素
【发布时间】:2014-02-25 10:07:47
【问题描述】:

我想在循环之前过滤集合元素。

当我尝试这个时:

foreach (CheckBox checkbox in this.Controls()
        .Where(c => c.GetType() == typeof (CheckBox)).Select(c => (CheckBox)c))

我收到以下错误:

"System.Windows.Forms.Controls cannot be used like a method."

我使用 .NET 框架 4 客户端配置文件,并且肯定在代码中使用 System.Linq

有什么想法吗?

【问题讨论】:

    标签: c# winforms linq


    【解决方案1】:

    this.Controls 是一个属性,而不是一个方法,所以你应该使用不带括号的()

    foreach (CheckBox checkbox in this.Controls
            .Where(c => c.GetType() == typeof (CheckBox)).Select(c => (CheckBox)c))
    

    编辑:根据您的评论,这不起作用。您可以使用以下代码:

    foreach (var control in this.Controls)
    {
        CheckBox myCheckbox = control as CheckBox;
        if (myCheckbox == null) continue;
    
        // your code
    }
    

    但我也更喜欢dkozi 的解决方案。

    【讨论】:

    • 谢谢。现在我明白了:'System.Windows.Forms.Control.ControlCollection' does not contain a definition for 'Where'
    【解决方案2】:

    Controls 是属性而不是方法,您也可以使用Enumerable.OfType<TResult> 方法更轻松地做到这一点:

    foreach (CheckBox checkbox in this.Controls.OfType<CheckBox>())
    {
    }
    

    【讨论】:

    • 我现在得到 2 个错误:Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'foreach statement cannot operate on variables of type 'method group' because 'method group' does not contain a public definition for 'GetEnumerator'
    • OfType后面加括号了吗?
    • 就是这样!谢谢!但是,为什么不能使用我的代码?我的代码适合什么样的收藏?提前致谢。
    • 如果ControlCollection 支持IEnumerable&lt;T&gt; 但仅支持IEnumerable,您的代码会很好。检查this问题
    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    相关资源
    最近更新 更多