How can I break a `RemoveAll()`statement in C# -
i'm using removeall()
statement, foreach element of list, , based in condition returned delegate, removes or not element list. this:
x.removeall(delegate(string y) { if (y == "abc") return true; return false; });
i want break foreach
removeall, upon fulfilling condition, no longer try remove elements. this:
x.removeall(delegate(string y) { if (foo() || bar()) break; //stop trying remove elements if (y == "abc") return true; return false; });
have way without auxiliary variable?
p.s: using auxiliary variable know how do.
there 2 real options. variable telling not remove more items:
var done = false; list.removeall(item => { if(done) return false; if(foo() || bar()) { done = true; return false; } return item == "abc"; }
or throwing exception (despite fact it's poor practice use exceptions control flow).
list.removeall(item => { if(foo() || bar()) throw new sometypeofexception() return item == "abc"; }
if foo or bar being true exceptional/error cases, maybe justify it, seems code smell. note technically going only way use removeall
, not invoke delegate on later items.
fundamentally problem operation you're trying perform isn't in line removeall
designed do. want version of method supports cancellation, or sufficient access internals of list create comparable method appropriate cancellation. sadly, don't have access underlying array in order able replicate ability of removeall
remove multiple items without moving of items until end, unless re-create own entire list based structure.
Comments
Post a Comment