-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
  • 38,126
  • 10
  • 70
  • 102
Donnoh
  • 144
  • 9

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
  • 38,126
  • 10
  • 70
  • 102
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
  • 27,818
  • 6
  • 51
  • 82