简体   繁体   中英

Nested foreach loops c#

        foreach (int i in a.set)
        {
            foreach (int k in b.set)
            {
                if (i < k)
                {
                    return true;                                
                }
                else if (i > k)
                {
                    return false;
                }
            }
        }


        return false;
    }

I got two sets, a set includes 3,4,6 b.set includes 3,4,5

The problem is that the outer loop only iterates once. But it contains 3 elements, why is that?

You return in your inner loop. This immediately exits the containing method.

  • i is 3 (the first element of a.set – let's assume that order for now).
    • k is 3 (same as above)
    • k is 4 – therefore the if condition in the inner loop is met and the method returns with true .

As you can see, you don't get the chance of iterating through all values of a.set before returning from the method.

使用“返回”指示的“中断”,它仅中断一个级别

这是因为您要通过在第一次迭代中返回一个值来退出foreach-loop

Based on the code and data you provided, the inner loop will exit the function with a return of true on the second iteration. There is no way in your code for the outer foreach to iterate more than once.

If you want to write code that returns true, if at any point set a has a number less than set b , you should do this:

foreach (int i in a.set)
{
    foreach (int k in b.set)
    {
        if (i < k)
        {
            return true;                                
        }
    }
}
return false;

也许您想使用break而不是return-当您返回(这将在3> 4时在内部循环的第二次迭代中发生)时,它将停止循环的执行并从您拥有的函数/方法中返回

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM