gpt4 book ai didi

c# - ListItemCollection 的 ForEach 扩展方法

转载 作者:太空狗 更新时间:2023-10-29 21:19:35 26 4
gpt4 key购买 nike

我实现了一个 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 中只能有一个项目符合此要求,但无论如何循环都已完成,解决此问题的最不丑陋的方法是什么?

谢谢。

最佳答案

你可以拿一个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"]));

关于c# - ListItemCollection 的 ForEach 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5831004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com