问题
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?
回答1:
Reference Linq:
using System.Linq;
And use this:
foreach (var control in Controls.Cast<Control>().Where(c => c is TextBox))
{
// ...
}
回答2:
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;
回答3:
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.
来源:https://stackoverflow.com/questions/47179959/using-lambda-function-in-a-foreach-over-controls