-1

I would like to translate this:

foreach(Control c in Controls)
{
    if(c is TextBox)
    {
        // ...
    }
}

Into:

foreach(Control c => (c is TextBox) in Controls)
{
    // ...
}

How can it be done using the lambda function specifically?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Donnoh
  • 161
  • 10

3 Answers3

8

Use OfType:

foreach (TextBox c in Controls.OfType<TextBox>())
{

}

It filters the elements of an IEnumerable based on a specified type.

Also don't forget to add LINQ to your using directives first:

using System.Linq;
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
3

Reference Linq:

using System.Linq;

And use this:

foreach (var control in Controls.Cast<Control>().Where(c => c is TextBox))
{
    // ...
}
0

You are looking for something like this:

foreach(TextBox ctrlTxtBox in Controls.OfType<TextBox>())
{
   // Got it code here
}

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

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88