-1

I have this below code and I am unable to convert it into a Linq because it is regarding winform controls

bool flag = false;
Panel x = (Panel)sender;

foreach(Control item in x.Controls)
{
    if(item is winformcontrol)
    {
       flag = true;
       break;
    }
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141

1 Answers1

1

Disregarding any other problem conceptual or otherwise

Since all you are doing is checking if a control is of a certain type, the easiest way is to use the Enumerable.OfType<TResult> method.

Filters the elements of an IEnumerable based on a specified type.

Then all that is needed is to call Enumerable.Any

Determines whether any element of a sequence exists or satisfies a condition.

Example

// lets check our cast and show off the new #9 pattern matching negation
if (sender is not Panel panel)
   throw new InvalidOperationException("Whoops");

var flag = panel
   .Controls
   .OfType<Something>()
   .Any();

...

The longer story is, ControlCollection.Controls only supports

  • IList
  • ICollection
  • IEnumerable (Non generic)

Not IEnumerable<T> so you are limited by what you can call.

However, IEnumerable<TResult> OfType<TResult>(this IEnumerable source) can take the non generic IEnumerable parameter, and returns an IEnumerable<T> giving you access to all of the extension methods you know and love.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
TheGeneral
  • 79,002
  • 9
  • 103
  • 141