Using lambda function in a foreach over controls [duplicate]

*爱你&永不变心* 提交于 2021-02-07 04:37:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!