Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop with conditions

Tags:

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.

like image 422
Naor Avatar asked Aug 13 '11 21:08

Naor


People also ask

How do you use foreach with conditions?

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.

Can we use foreach instead of for loop?

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.

What can foreach statements iterate through?

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.

When to use foreach loop explain it with an example?

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: <?


1 Answers

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 } 
like image 100
dtb Avatar answered Sep 23 '22 03:09

dtb