对于ListItemCollection的ForEach扩展方法 [英] ForEach Extension Method for ListItemCollection

查看:252
本文介绍了对于ListItemCollection的ForEach扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个ExtensionMethod基本上可以作为的foreach循环,我的实现是这样的:

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



这样做的问题是,只能是相匹配这一要求将DropDownList内的一个项目,但循环正在结束,无论如何,这将是最丑陋的方式来解决这个问题?

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?

感谢。

推荐答案

您可以采取 Func键<列表项,布尔> 代替动作<列表项> 并打破循环,如果它返回真正

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

您可以使用它像这样

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

这篇关于对于ListItemCollection的ForEach扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆