0

I would like to filter the collection elements before I loop on each.

When I try this:

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

I get the following error:

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

I use .NET framework 4 client-profile and for sure use System.Linq in code.

Any ideas?

user3165438
  • 2,631
  • 7
  • 34
  • 54

2 Answers2

4

this.Controls is a property, not a method, so you should use it without the brackets ().

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

Edit: Based on your comment this does not work. What you could use is the following code:

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

    // your code
}

But I would also prefer the solution from dkozi.

Community
  • 1
  • 1
Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47
  • Thanks. Now I get this: `'System.Windows.Forms.Control.ControlCollection' does not contain a definition for 'Where'` – user3165438 Feb 25 '14 at 10:11
3

Controls is a property not a method also you can can do it much easier with Enumerable.OfType<TResult> method:

foreach (CheckBox checkbox in this.Controls.OfType<CheckBox>())
{
}
dkozl
  • 32,814
  • 8
  • 87
  • 89
  • I get now 2 errors: `Foreach cannot operate on a 'method group'. Did you intend to invoke the 'method group'` and `foreach statement cannot operate on variables of type 'method group' because 'method group' does not contain a public definition for 'GetEnumerator'` – user3165438 Feb 25 '14 at 10:13
  • Do you put brackets after `OfType`? – dkozl Feb 25 '14 at 10:17
  • That's the spot! Thanks! However, why cannot use my code? My code is appropriate to what sort of collection? Thanks in advance. – user3165438 Feb 25 '14 at 10:21
  • Your code would be fine if `ControlCollection` would support `IEnumerable` but is supports only `IEnumerable`. Check [this](http://stackoverflow.com/questions/3302435/why-doesnt-the-controls-collection-provide-all-of-the-ienumerable-methods) question – dkozl Feb 25 '14 at 10:26