Saturday, 15 June 2013

c# - How to avoid Iterator method being restarted? -



c# - How to avoid Iterator method being restarted? -

please consider next c# block:

int resultindex = 0; result firstresult = results.first(); doaveryimportoperationwithfirstresult(firstresult); console.writeline(string.format("this {0} result.", resultindex++)); yield homecoming firstresult; foreach(result result in results) { console.writeline(string.format("this {0} result.", resultindex++)); yield homecoming result; }

if familiarized linq , iterators, you'll notice in first iteration of foreach block, first result results returned instead of sec one.

so, problem: can't first value iterator method utilize somewhere else without restarting method.

someone know workaround this?

others have shown approach using foreach loop , conditional execution. that's neat approach - here's alternative in case foreach loop inappropriate whatever reason.

using (var iterator = results.getenumerator()) { if (!iterator.movenext()) { // throw appropriate exception here. } result firstresult = iterator.current; doaveryimportoperationwithfirstresult(firstresult); console.writeline(string.format("this {0} result.", resultindex++)); yield homecoming firstresult; while (iterator.movenext()) { result result = iterator.current; console.writeline(string.format("this {0} result.", resultindex++)); yield homecoming result; } }

c# linq iterator yield-return

No comments:

Post a Comment