【问题标题】:Question About Foreach and List Iteration关于 Foreach 和 List 迭代的问题
【发布时间】:2011-09-10 22:59:05
【问题描述】:

我一直在阅读有关 foreach 和列表迭代的信息,并且我了解如何设置它。

我在整个研究过程中未能找到的是如何进行多次迭代。为了更好地解释,这里是我的具体例子:

我正在创建一个 A* 路径请求管理器,它将给定数量的搜索周期分配给每个请求。因此它需要遍历其LinkedList 的请求,为每个请求分配一个搜索周期。鉴于它以 1000 个周期开始,不用说,它需要多次检查其请求列表才能平均分配其所有周期。

如何确保列表将继续迭代?对于whilefor 循环,这会是一个更好的任务吗?或者有没有办法通过foreach 做到这一点?

如果它可以帮助任何人进一步理解我的问题,这是我现在拥有的代码:

    //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 == SearchStatus.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

【问题讨论】:

    标签: c# list foreach linked-list iteration


    【解决方案1】:

    我不会为此使用列表,而是使用 QueueConcurrentQueue - 你 Enqueue 例如 1000 个请求......然后你使用带有 Count > 0 条件的 while 循环进行迭代它的内容......你Dequeue一个请求并执行它......如果它需要重新执行,那么你只需Enqueue它再次......这样它将被添加回来但到最后所以执行保持公平/均匀。

    【讨论】:

    • 我才刚接触 C# 一周,还没有听说过内置队列。感谢您向我指出这一点 - 现在我可以研究更多。
    【解决方案2】:

    您不能修改正在迭代的集合,以下代码会在运行时抛出异常:

        foreach (Pathfinder request in this.searchRequests)
        {
             //remove this request from the queue
             this.searchRequests.Remove(request);
        } //end foreach
    

    为了多次迭代,请将您的 foreach 放在另一个循环结构中。毕竟,foreach 似乎不是适合这里工作的工具。

    【讨论】:

    • 谢谢。那么将while循环放在foreach之外会更好吗?
    • 关于删除已完成/失败的搜索,我理解您所说的在迭代时修改列表的内容。但是,那么,我如何在列表中移动以查找已完成/失败的请求并将其删除?
    • 可能,但是在遍历它时仍然无法从 searchRequest 中删除请求。您可以将它们存储在 requestToRemoves 集合中,并在 foreach 之后将它们全部删除。
    • 我明白了。然后我会在从第一个列表中删除的同时迭代第二个列表。完美,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-02-16
    • 2019-05-07
    • 1970-01-01
    • 2016-01-10
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多