How to use OfType

0

In a single Oftype you can do several searches like TextBox, ComboBox, etc.

foreach (Control c in frm.Controls.OfType<TextBox>())

I want to achieve something like this

foreach (Control c in frm.Controls.OfType<TextBox || TextBox || CheckBox>())

Can you search through several controls?

    
asked by Pedro Ávila 16.10.2016 в 04:39
source

2 answers

0

As indicated by @sstan it is not possible to use OfType to filter by several types of controls. Modify your code by adding Cast ()

foreach (Control c in frm.Controls.Cast<Control>().Where(ctl => ctl is TextBox || ctl is CheckBox))

You can also declare an extension method to filter by several types of control more or less like this

using System.Collections;

public static class MyExtensions
{
    public static IEnumerable OfType<T1, T2>(this IEnumerable source)
    {
        foreach (object item in source)
        {
            if (item is T1 || item is T2)
            {
                yield return item;
            }
        }
    }
}
    
answered by 16.10.2016 / 17:22
source
2

No, it is not possible to combine several types with OfType . To do what you want, you would have to convert the logic using Where :

foreach (Control c in frm.Controls.Where(ctl => ctl is TextBox || ctl is CheckBox))
    
answered by 16.10.2016 в 17:11