I implemented an ExtensionMethod which basically works as ForEach-Loop, my Implementation looks like this:
public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
foreach (ListItem item in collection)
act(item);
}
However, I'd like the method to stop looping after the first time a specific condition is met.
Here's how I currently use it:
ddlProcesses.Items.ForEach(item => item.Selected = item.Value == Request["Process"]?true:false);
The Problem with this is that there can only be one item inside the DropDownList which matches this requirement, but the loop is being finished anyway, what would be the least ugly way to solve this problem?
Thanks.
You can take a Func<ListItem, bool>
instead of an Action<ListItem>
and break the loop if it returns true
:
public static void ForEach(this ListItemCollection collection,
Func<ListItem, bool> func)
{
foreach (ListItem item in collection) {
if (func(item)) {
break;
}
}
}
You can use it like this:
ddlProcesses.Items.ForEach(
item => item.Selected = (item.Value == Request["Process"]));
public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
foreach (ListItem item in collection)
{
act(item);
if(condition) break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With