score:5

Accepted answer

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"]));

score:1

First do this:

IEnumerable<ListItem> e = ddlProcesses.Items.OfType<ListItem>(); // or Cast<ListItem>()

to get generic collection.

Then use can roll your own, generic extension method:

public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
{
    foreach (T item in collection) action(item);
}

public static void ForEach<T>(this IEnumerable<T> collection, Func<T> func)
{
    foreach (T item in collection) if (func(item)) return;
}

Anyway, cache lookup result:

var process = Request["Process"];

e.ForEach(i => i.Selected = i.Value == process);

score:1

Your requirements are not 100% clear. Do you need to process all items to set them to false except the only one which matches the condition or do you just want to find the with the right condition or do you want to apply a function until a condition is met?

  1. Only do something to an item the first time the condition matches

    public static void ApplyFirst(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           if (predicate(item))
           {
               action(item);
               return;
           }
        }
    }
    
  2. Do something to an item everytime a condition matches

    public static void ApplyIf(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           if (predicate(item))
           {
               action(item);
           }
        }
    }
    
  3. Do something to all items until a condition matches

    public static void ApplyUntil(this ListItemCollection collection,
                          Action<ListItem> action, Func<ListItem, bool> predicate)
    {
        foreach (ListItem item in collection) 
        {
           action(item);
           if (predicate(item))
           {
               return;
           }
        }
    }
    

score:2

public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
    foreach (ListItem item in collection)
    {
        act(item);
        if(condition) break;
    }
}

Related Query

More Query from same tag