ListItemCollection的ForEach扩展方法

时间:2011-04-29 10:41:37

标签: c# .net linq extension-methods listitem

我实现了一个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 个答案:

答案 0 :(得分:5)

您可以使用Func<ListItem, bool>代替Action<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"]));

答案 1 :(得分:2)

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

答案 2 :(得分:1)

首先这样做:

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

获取通用集合。

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

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

var process = Request["Process"];

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

答案 3 :(得分: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;
           }
        }
    }