As others have posted, you can't exit the loop in ForEach.

Are you able to use LINQ? If so, you could easily combine TakeWhile and a custom ForEach extension method (which just about every project seems to have these days).

In your example, however, List<T>.FindIndex would be the best alternative - but if you're not actually doing that, please post an example of what you really want to do.

Answer from Jon Skeet on Stack Overflow
Discussions

c# - How can i exit the LINQ foreach loop when some condition fails - Stack Overflow
I've implemented LINQ foreach loop to execute some operation and if some condition fails in it i want to exit from that point and display an error to the user and don't want to go forward. Below is More on stackoverflow.com
๐ŸŒ stackoverflow.com
C# Break out of foreach loop after X number of items - Stack Overflow
In my foreach loop I would like to stop after 50 items, how would you break out of this foreach loop when I reach the 50th item? Thanks foreach (ListViewItem lvi in listView.Items) More on stackoverflow.com
๐ŸŒ stackoverflow.com
Linq return whole method not just the filter.
Looking at the name of your functions, I think you want the Any LINQ method. It takes a boolean function/lambda and returns true if anything returns true. It should also short circuit, i.e. it stops looking the second it finds a matching item. More on reddit.com
๐ŸŒ r/csharp
19
5
October 23, 2022
c# - ForEach() : Why can't use break/continue inside - Stack Overflow
Have a read of how the yield keyword ... how LINQ queries operate. It's too long to explain here, but no, not all the items must be checked; only as many items as are requested by the call-chain will be checked. Exactly the same as your FirstOrDefault, which will iterate until it hits a match. 2010-12-14T16:59:43.697Z+00:00 ... Because ForEach is a method and not a regular foreach loop is need iterate over lstTemp with a regular foreach loop in case break, but in case ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 28, 2014
๐ŸŒ
Aspose
forum.aspose.com โ€บ aspose.words product family
How to break out of a foreach loop? - Free Support Forum - aspose.com
July 3, 2019 - 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 ...
๐ŸŒ
CodinGame
codingame.com โ€บ playgrounds โ€บ 345 โ€บ c-linq-background-topics โ€บ exiting-a-generator
Coding Games and Programming Challenges to Code Better
CodinGame is a challenge-based training platform for programmers where you can play with the hottest programming topics. Solve games, code AI bots, learn from your peers, have fun.
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ mastering-break-continue-c-foreach-loops-milos-tanaskovic-kffkf
Mastering break and continue in C# foreach Loops
February 9, 2025 - Dictionary<string, int> employees = new Dictionary<string, int> { { "Alice", 5000 }, { "Bob", 4000 }, { "Charlie", 6000 }, { "David", 7000 } }; foreach (var employee in employees) { if (employee.Value < 5000) { Console.WriteLine($"Skipping {employee.Key} (low salary)"); continue; } Console.WriteLine($"Processing {employee.Key} - Salary: {employee.Value}"); if (employee.Key == "Charlie") { Console.WriteLine("Stopping loop after processing Charlie."); break; } } Payroll processing: Skip over employees who donโ€™t meet a salary threshold. Conditional stopping: Cease iteration after a certain empl
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ csharp โ€บ csharp exit foreach
How to Exit a Foreach Loop in C# | Delft Stack
March 11, 2025 - This method is particularly useful when you are searching for a specific item or condition and want to stop processing once it is found. Another way to exit a foreach loop, especially when you are inside a method, is by using the return statement.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/csharp โ€บ linq return whole method not just the filter.
r/csharp on Reddit: Linq return whole method not just the filter.
October 23, 2022 -

Hey guys, noob question but how do i return from inside a Linq For loop. I have something like this

recipe.RequiredItem.ToList().ForEach(item => {
    if (!save.PlayerStall.Inventory.ContainsKey(item.Key.UUID)){
        //Notification code
        return;
    }
});

The issue is that the return seems to Only kick out of the loop not the whole method so the code under this which then actually crafts the item runs anyway. I have thought about just a bool at the top called CanCraft or something and setting that so when the loop exists I check if can craft and return then. but that seems wrong, I feel Linq must have a way to fully escape right!???

Top answer
1 of 5
13
Looking at the name of your functions, I think you want the Any LINQ method. It takes a boolean function/lambda and returns true if anything returns true. It should also short circuit, i.e. it stops looking the second it finds a matching item.
2 of 5
9
Unfortunately there isn't a built in Linq method. The closest is the TakeWhile method but you want the last missing item to be included in the loop. You can either rewrite your loop: void Original(){ Console.WriteLine("Original"); recipe.RequiredItem.ToList().ForEach(item => { Console.WriteLine(item); if (!save.PlayerStall.Inventory.ContainsKey(item.Key.UUID)){ //Notification code return; } }); } into a real foreach loop: void Loop(){ Console.WriteLine("Loop"); foreach(var item in recipe.RequiredItem){ Console.WriteLine(item); if (!save.PlayerStall.Inventory.ContainsKey(item.Key.UUID)){ //Notification code return; } } } or you could write your own Linq extension and use that: void TakeUntil(){ Console.WriteLine("TakeUntil"); recipe.RequiredItem.TakeUntil(item => save.PlayerStall.Inventory.ContainsKey(item.Key.UUID)).ToList().ForEach(item => { Console.WriteLine(item); }); } Here is an example of an extension method that seems to suit your purpose: public static class EnumerableExtensions { public static IEnumerable TakeUntil(this IEnumerable items, Func predicate){ foreach(var item in items){ yield return item; if(!predicate(item)) break; } } } P.S. List.ForEach is not part of Linq and shouldn't be encouraged. If you want to loop over items just use a normal foreach loop, so you can break, continue, return correctly. Here is a short program demonstrating the behaviour of each: https://dotnetfiddle.net/0QEATp
๐ŸŒ
CodeGenes
codegenes.net โ€บ blog โ€บ how-do-i-jump-out-of-a-foreach-loop-in-c
How to Break Out of a foreach Loop in C# When an Element Meets Requirements: A Quick Guide โ€” codegenes.net
Modifying the Collection: Never add/remove elements inside a foreach loop (throws InvalidOperationException). Use a for loop or create a copy of the collection first. Overusing break: Excessive break statements can make code hard to follow. Prefer LINQ for simple existence checks.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ archive โ€บ msdn-technet-forums โ€บ c6638214-fcf3-4883-a3ba-6296f697efda
Breaking out of a Linq ForEach Loop | Microsoft Learn
policySearch.ForEach(delegate(spPolicyBrowserSearch_Result policy) { if (ProcessCancellation(Row)) { break; } }); However, I receive an error on the break command stating that 'there is no enclosing loop out of which to break or continue' Wednesday, ...
๐ŸŒ
Devleader
devleader.ca โ€บ 2024 โ€บ 01 โ€บ 03 โ€บ understanding-foreach-loops-in-c-what-you-need-to-know
Understanding foreach Loops in C# - What You Need To Know
January 3, 2024 - Break can be used to exit out of the loop completely, while continue can be used to skip the current iteration and move onto the next one. These statements can be helpful for improving code readability and simplifying error-checking.
๐ŸŒ
TradingCode
tradingcode.net โ€บ csharp โ€บ loop โ€บ break
How to stop a loop early? C#'s break statement explained
C#'s break statement immediately ends a loop. This article explains the details and shows how to use it with for, while, do-while, and foreach loops.
๐ŸŒ
TradingCode
tradingcode.net โ€บ csharp โ€บ loop โ€บ foreach-linq
Change C# foreach loop with LINQ methods โ€ข TradingCode
Some C# loops make it easy to skip values. With the for loop or the while loop we can simply start our index count at 1 rather than 0. But foreach has no such thing. So how to skip the first element? The Skip() LINQ method excludes an arbitrary number of elements from the start of a collection.
๐ŸŒ
Reddit
reddit.com โ€บ r/csharp โ€บ better ways to loop through multiple levels of lists rather than nested foreach loops?
r/csharp on Reddit: Better ways to loop through multiple levels of Lists rather than nested foreach loops?
January 31, 2024 -

I am working with some objects that have a number of nested properties including lists which have other List<ObjA>. When trying to read the lowest level of data I get this:

foreach (ISOTLG tlg in isoxml.TimeLogs.Values)

{

foreach(TLGDataLogLine dll in tlg.Entries)

{

foreach(TLGDataLogEntry entry in dll.Entries)

{

Console.WriteLine($"POS EAST: {dll.PosEast} POS NORTH:{dll.PosNorth}");

}

}

}

Is there a prettier way or better way to do this? If I go all the way down Ill have 8 nested foreach loops

๐ŸŒ
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 statement.