Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ForEach Extension Method for ListItemCollection

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.

like image 666
Dennis Röttger Avatar asked Apr 29 '11 10:04

Dennis Röttger


2 Answers

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"]));
like image 167
Frédéric Hamidi Avatar answered Sep 23 '22 02:09

Frédéric Hamidi


public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
    foreach (ListItem item in collection)
    {
        act(item);
        if(condition) break;
    }
}
like image 21
Gabriel Avatar answered Sep 21 '22 02:09

Gabriel