问题
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);
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?
Thanks.
回答1:
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"]));
回答2:
public static void ForEach(this ListItemCollection collection, Action<ListItem> act )
{
foreach (ListItem item in collection)
{
act(item);
if(condition) break;
}
}
回答3:
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);
回答4:
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?
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; } } }
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); } } }
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; } } }
来源:https://stackoverflow.com/questions/5831004/foreach-extension-method-for-listitemcollection