Foreach loop with a condition

收藏待读

Foreach loop with a condition

Is there a way to do the following in one statement?

foreach(CheckBox subset in groupBox_subset.Controls)
    if(subset.Checked) { ... }

Sure:

foreach (CheckBox subset in groupBox_subset.Controls
                                           .Cast()
                                           .Where(c => c.Checked))
{
   ...
}

The Cast call is required because the Controls property only implements IEnumerable , not IEnumerable , but LINQ basically works on strongly-typed collections. In other words, your existing code is actually closer to:

foreach(Object tmp in groupBox_subset.Controls)
{
    CheckBox subset = (CheckBox) tmp;
    if(subset.Checked) { ... }
}

If you want to be able to ignore non- CheckBox controls, you want the OfType method instead of Cast in the top snippet:

foreach (CheckBox subset in groupBox_subset.Controls
                                           .OfType()
                                           .Where(c => c.Checked))
{
   ...
}

原文 : Hello, buddy!

相關閱讀

免责声明:本文内容来源于Hello, buddy!,已注明原文出处和链接,文章观点不代表立场,如若侵犯到您的权益,或涉不实谣言,敬请向我们提出检举。