I can do loop with more then one condition like this:
for (int i = 0; condition1 && condition2 && ... && conditionN ; i++) { }
Is there any way to do it using foreach:
foreach (var i in arr and while condition1 && condition2 && ... && conditionN) { }
But without using break;
?
I need this in order to pass on Enumerable and I don't want continue iterations if my condition is not true.
Prerequisite: Loops in C#The resulting condition should be true to execute statements within loops. The foreach loop is used to iterate over the elements of the collection. The collection may be an array or a list. It executes for each element present in the array.
forEach loop: The forEach() method is also used to loop through arrays, but it uses a function differently than the classic “for loop”. It passes a callback function for each element of an array together with the below parameters: Current Value (required): The value of the current array element.
The foreach loop in C# iterates items in a collection, like an array or a list. It proves useful for traversing through each element in the collection and displaying them. The foreach loop is an easier and more readable alternative to for loop.
The foreach loop is mainly used for looping through the values of an array. It loops over the array, and each value for the current array element is assigned to $value, and the array pointer is advanced by one to go the next element in the array. Syntax: <?
You can use the Enumerable.TakeWhile Extension Method:
foreach (var i in arr.TakeWhile(j => condition1 && ... && conditionN)) { // do something }
This is roughly equivalent to:
foreach (var j in arr) { if (!(condition1 && ... && conditionN)) { break; } var i = j; // do something }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With