6

我实现了一个 ExtensionMethod,它基本上作为 ForEach-Loop 工作,我的实现如下所示:

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

但是,我希望在第一次满足特定条件后停止循环的方法。

这是我目前使用它的方式:

ddlProcesses.Items.ForEach(item => item.Selected = item.Value == Request["Process"]?true:false);

这样做的问题是 DropDownList 中只能有一个项目符合此要求,但循环无论如何都已完成,解决此问题的最不难看的方法是什么?

谢谢。

4

4 回答 4

5

如果它返回,您可以使用 aFunc<ListItem, bool>而不是 anAction<ListItem>并中断循环true

public static void ForEach(this ListItemCollection collection,
    Func<ListItem, bool> func)
{
    foreach (ListItem item in collection) {
        if (func(item)) {
            break;
        }
    }
}

你可以像这样使用它:

ddlProcesses.Items.ForEach(
    item => item.Selected = (item.Value == Request["Process"]));
于 2011-04-29T10:45:56.537 回答
2
public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
    foreach (ListItem item in collection)
    {
        act(item);
        if(condition) break;
    }
}
于 2011-04-29T10:47:47.813 回答
1

首先这样做:

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

获得通用集合。

然后使用可以滚动您自己的通用扩展方法

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;
}

无论如何,缓存查找结果:

var process = Request["Process"];

e.ForEach(i => i.Selected = i.Value == process);
于 2011-04-29T10:46:12.963 回答
1

您的要求不是 100% 明确的。您是否需要处理所有项目以将它们设置为 false 除了唯一与条件匹配的项目,还是只想找到具有正确条件的项目,或者您想应用一个函数直到满足条件?

  1. 仅在条件第一次匹配时对项目执行操作

    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. 每次条件匹配时对项目执行操作

    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. 对所有项目执行某些操作,直到条件匹配

    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;
           }
        }
    }
    
于 2011-04-29T11:16:28.803 回答