foreach (string s in sList)
{
    if (s.equals("ok"))
        return true;
}

return false;

Alternatively, if you need to do some other things after you've found the item:

bool found = false;
foreach (string s in sList)
{
    if (s.equals("ok"))
    {
        found = true;
        break; // get out of the loop
    }
}

// do stuff

return found;
Answer from mbillard on Stack Overflow
Top answer
1 of 6
19

I think for simple loops, such as these, the standard first syntax is much clearer. Some people consider multiple returns confusing or a code smell, but for a piece of code this small, I do not believe this is a real issue.

It gets a bit more debatable for more complex loops. If the loop's contents cannot fit on your screen and has several returns in the loop, there is an argument to be made that the multiple exit points can make the code more difficult to maintain. For example, if you had to ensure some state maintenance method ran before exiting the function, it would be easy to miss adding it to one of the return statements and you would cause a bug. If all the end conditions can be checked in a while loop, you only have one exit point and can add this code after it.

That said, with loops especially it is good to try and put as much logic as possible into separate methods. This avoids a lot of cases where the second method would have advantages. Lean loops with clearly separated logic will matter more than which of these styles you use. Also, if most of your application's code base is using one style, you should stick with that style.

2 of 6
56

This is easy.

Almost nothing matters more than clarity to the reader. The first variant I found incredibly simple and clear.

The second 'improved' version, I had to read several times and make sure all the edge conditions were right.

There is ZERO DOUBT which is better coding style (the first is much better).

Now - what is CLEAR to people may vary from person to person. I'm not sure there are any objective standards for that (though posting to a forum like this and getting a variety of peoples inputs can help).

In this particular case, however, I can tell you why the first algorithm is more clear: I know what the C++ iterate over a container syntax looks like and does. I've internalized it. Someone UNFAMILIAR (its new syntax) with that syntax might prefer the second variation.

But once you know and understand that new syntax, its a basic concept you can just use. With the loop iteration (second) approach, you have to carefully check that the user is CORRECTLY checking for all the edge conditions to loop over the entire array (e.g. less than in stead of less-or-equal, same index used for test and for indexing etc).

Discussions

jsp - JSTL continue, break inside foreach - Stack Overflow
I like this idea of having the variable on the foreach, and setting it to the end of the loop to exit with a c:set ... if you structure a begin and an end for loop. https://www.codesenior.com/en/tutorial/How-To-Break-Foreach-Loop-in-JSP More on stackoverflow.com
🌐 stackoverflow.com
Re: How to break a loop in JSTL c:foreach- ...
Email display mode: · Modern rendering · Legacy rendering · This site requires JavaScript enabled. Please enable it More on lists.apache.org
🌐 lists.apache.org
How to break out of a foreach loop? - Free Support Forum - aspose.com
The Template Syntax page explains using a foreach loop, which I have done successfully. However, sometimes when I find a match in the loop, I want to break out of the loop and move on to the next part of the code. In C#, you can use the break or return statement to do this, but that doesn’t ... More on forum.aspose.com
🌐 forum.aspose.com
1
0
July 3, 2019
Need help with nested loop (c:forEach) tags. Can I break from inner loop? - Oracle Forums
Hi all, I have this annoying problem and I am looking for any suggestions. I have 2 select boxes. One is for all available users, and second - for selected users (designated as admins). The list of a... More on forums.oracle.com
🌐 forums.oracle.com
February 13, 2006
🌐
Coderanch
coderanch.com › t › 286701 › java › break-forEach-iteration
How to break c:forEach iteration? (JSP forum at Coderanch)
I'm looking to the solution to break the c:forEach loop, similar to the below in pure Java: while(condition){ ... break; } I did not find any attribute in forEach tag to break the loop easily.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › statements › iteration-statements
Iteration statements -for, foreach, do, and while - C# reference | Microsoft Learn
January 20, 2026 - The do statement conditionally executes its body one or more times. The while statement conditionally executes its body zero or more times. At any point within the body of an iteration statement, you can exit the loop by using the break ...
🌐
TutorialsPoint
tutorialspoint.com › home › jsp › jstl core foreach tag
JSTL Core foreach Tag
September 26, 2010 - The <c:forEach> tag is a commonly used tag because it iterates over a collection of objects. The <c:forTokens> tag is used to break a string into tokens and iterate through each of the tokens.
🌐
W3Schools
w3schools.com › cs › cs_break.php
C# Break and Continue
For loop Foreach loop C# Break/Continue C# Arrays · Arrays Loop through an array Sort arrays Multidimensional arrays · C# Methods C# Method Parameters · Parameters Default Parameter Return Values Named Arguments C# Method Overloading · C# OOP C# Classes/Objects ·
Find elsewhere
🌐
Apache
lists.apache.org › thread › zbr14795h17scbl7ctck4qmbqtf7h7vo
Re: How to break a loop in JSTL c:foreach- ...
Email display mode: · Modern rendering · Legacy rendering · This site requires JavaScript enabled. Please enable it
🌐
DEV Community
dev.to › mayankav › why-you-can-t-break-out-of-the-foreach-loop-n5e
Why can't you break out of the forEach loop? - DEV Community
September 29, 2021 - You can't break from forEach because that's the purpose of forEach loop. In JS you have reduce, map, while, do while, for, filter and god knows how many other types of loops. The reason for forEach to exist is to NOT allow you to break from it!
🌐
C# Corner
c-sharpcorner.com › UploadFile › efa3cf › break-vs-continue-in-C-Sharp
Break Vs Continue in C#
November 2, 2023 - Break (breaks the loop/switch) Break statement is used to terminate the current loop iteration or terminate the switch statement in which it appears. Break statement can be used in the following scenarios: for loop (For loop & nested for loop ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › forEach
Array.prototype.forEach() - JavaScript - MDN Web Docs
The forEach() method of Array instances executes a provided function once for each array element. const array = ["a", "b", "c"]; array.forEach((element) => console.log(element)); // Expected output: "a" // Expected output: "b" // Expected output: "c"
🌐
Aspose
forum.aspose.com › aspose.words product family
How to break out of a foreach loop? - Free Support Forum - aspose.com
July 3, 2019 - The Template Syntax page explains using a foreach loop, which I have done successfully. However, sometimes when I find a match in the loop, I want to break out of the loop and move on to the next part of the code. In C#, you can use the break or return statement to do this, but that doesn’t ...
🌐
Oracle
forums.oracle.com › ords › apexds › post › need-help-with-nested-loop-c-foreach-tags-can-i-break-from-3268
Need help with nested loop (c:forEach) tags. Can I break from inner loop? - Oracle Forums
February 13, 2006 - Hi all, I have this annoying problem and I am looking for any suggestions. I have 2 select boxes. One is for all available users, and second - for selected users (designated as admins). The list of a...
🌐
Programiz
programiz.com › csharp-programming › break-statement
C# break Statement (With Examples)
In the above example, we have created an array with values: 1, 2, 3, 4, 5. Here, we have used the foreach loop to print each element of the array. However, the loop only prints 1 and 2. This is because when the number is equal to 3, the break statement is executed.
🌐
CMake
cmake.org › cmake › help › latest › command › foreach.html
foreach — CMake 4.3.0 Documentation
Once the endforeach is evaluated, ... to the loop scope. See policy CMP0124 for details. The commands break() and continue() provide means to escape from the normal control flow....