【问题标题】:C# List loop within a loop?循环内的C#列表循环?
【发布时间】:2018-11-09 15:29:07
【问题描述】:

我正在做一个课堂项目,这就是我目前所做的。我知道代码在找到匹配项时返回 true,但我希望它继续循环,直到找不到更多实例。

我在for/while 循环中查看了许多站点,但我似乎无法正确获取语法和/或在应用逻辑时它不起作用。

public bool Remove(T toRemove)
{
    for (int i = 0; i < count; i++)
    {
        if (items[i].Equals(toRemove))
        {
            int removeIndex = i;
            for (int j = removeIndex; j < count - 1; j++)
            {
                items[j] = items[j + 1];
            }
            return true;
        }
    }
    return false;
}

【问题讨论】:

  • 使用布尔变量,如果找到项目,则将其设置为 true,然后继续循环,直到遍历所有元素,然后返回布尔值。
  • 太棒了,没想到。做到了,非常感谢。

标签: c# loops for-loop


【解决方案1】:

如果要完成循环,请不要返回。而是将结果保存在最后应该返回的 var 上:

    public bool Remove(T toRemove)
    {
        bool result = false;
        for (int i = 0; i < count; i++)
        {
            if (items[i].Equals(toRemove))
            {
                int removeIndex = i;
                for (int j = removeIndex; j < count - 1; j++)
                {
                    items[j] = items[j + 1];
                }
                result = true;
            }
        }
        return result;
    }

【讨论】:

    【解决方案2】:

    只需将结果保存在一个变量中,循环完成后返回即可:

    public bool Remove(T toRemove)
    {
        bool result = false;
        for (int i = 0; i < count; i++)
        {
            if (items[i].Equals(toRemove))
            {
                int removeIndex = i;
                for (int j = removeIndex; j < count - 1; j++)
                {
                    items[j] = items[j + 1];
                }
                result = true;
            }
        }
        return result;
    }
    

    【讨论】:

    • 我认为您的意思是 bool 而不是 boolean
    • @TânNguyễn true 'dat。暂时注意力不集中,感谢您的注意。
    【解决方案3】:
    //Use a boolean variable and set it to true if an item is found, 
    //and continue your loop until you go through all elements, then return the boolean value.  
    
    public bool Remove(T toRemove)
    {
            bool match= false; //boolean to track if any match is found
            for (int i = 0; i < count; i++)
            {
                if (items[i].Equals(toRemove))
                {
                    int removeIndex = i;
                    for (int j = removeIndex; j < count - 1; j++)
                    {
                        items[j] = items[j + 1];
                    }
                    match= true;
                }
            }
    
            return match;
    }
    

    【讨论】:

      【解决方案4】:

      我认为您想要做的是声明一个名为“结果”的布尔值并将其实例化为 false。在返回 true 的循环中,将“result”设置为 true。最后,在你返回 false 的地方,返回“result”

      【讨论】:

        猜你喜欢
        • 2018-01-11
        • 1970-01-01
        • 2011-08-03
        • 1970-01-01
        • 1970-01-01
        • 2016-12-31
        • 2021-12-20
        • 1970-01-01
        • 2012-12-22
        相关资源
        最近更新 更多