Question About Foreach and List Iteration
I've been reading about foreach
and list iteration, and I understand how to set it up.
What I have not been able to find throughout my research is how to iterate more than once. To better explain, here is my specific example:
I'm creating an A* path request manager that divides a given number of search cycles out over each request. So it will need to iterate through its LinkedList
of requests, handing out one search cycle per request. Given that it starts with 1000 cycles, needless to say, it will need to go through its list of requests more than once in order to evenly distribute all of its cycles.
How can I ensure that the list will continue to iterate? Would this be a better task for a while
or for
loop? Or is there a way to do it with foreach
?
In the event it would help anyone to further understand my question, here is my code as I have it now:
//Method: UpdateSearches()
//Purpose: to distribute all available search cycles
// between all active searches
// if a search completes or fails during this
// update, this method will notify the pathfinder
// who made the request
//Parameters: none
//Returns: nothing
public void UpdateSearches()
{
//start off with a full number of cycles
int cyclesRemaining = this.searchCyclesPerUpdate;
//cycle through all active requests
foreach (Pathfinder request in this.searchRequests)
{
while ((cyclesRemaining > 0) &&
(this.searchRequests.Count != 0))
{
//one search cycle
SearchStatus result = request.OneCycle();
//if the search completes (success or failure)
if (result == SearchStat开发者_如何学运维us.targetFound ||
result == SearchStatus.targetNotFound)
{
//remove this request from the queue
this.searchRequests.Remove(request);
} //end if
//move on to the next request
cyclesRemaining--;
} //end while
} //end foreach
} //end method
I would not use a List for this but a Queue
or ConcurrentQueue
- you Enqueue
for example the 1000 requests... then you use a while
loop with a condition on Count > 0
to iterate the content of it... you Dequeue
a request and execute it... if it needs to be re-executed then you just Enqueue
it again... this way it will be added back but to the end so the execution stays fair/even.
You cannot modify a collection that you are iterating, the following code would throw an exception at runtime:
foreach (Pathfinder request in this.searchRequests)
{
//remove this request from the queue
this.searchRequests.Remove(request);
} //end foreach
In order to iterate more than once, place your foreach within another loop construction. After all, doesn't seem that foreach is the right tool for the job here.
精彩评论