Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a 'foreach' loop to have a condition check?

Tags:

c#

foreach

If I have a foreach loop, is there any way to check a boolean as well?

I don't want to check once inside the foreach() and then break for example. I want to foreach over a collection and at the same time evaluate if something is true.

For example, I don't want to do:

    IEnumerable<Job> jobs = currentJobs;      foreach(Job job in jobs)     {         if (found)              break;     } 
like image 263
adamwtiko Avatar asked Dec 02 '10 14:12

adamwtiko


People also ask

What can foreach loops not be used for?

For-each cannot be used to initialize any array or Collection, because it loops over the current contents of the array or Collection, giving you each value one at a time. The variable in a for-each is not a proxy for an array or Collection reference.

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.

Can a foreach loop be infinite?

A foreach loop is intended to iterate over a list with a finite number of elements. You do not want that to run forever. To do that, one uses a while or a do loop. Probably not exactly what you're looking for, but it is technically possible to have a foreach run forever.

What is difference between regular for loop and foreach loop?

The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.


2 Answers

I found another approach:

        foreach (var car in cars) if (!rentedCars.Contains(car))         {             // Magic         } 
like image 166
David Diez Avatar answered Oct 17 '22 09:10

David Diez


Try using TakeWhile.

From the example:

    string[] fruits = { "apple", "banana", "mango", "orange",                            "passionfruit", "grape" };      IEnumerable<string> query =         fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);      foreach (string fruit in query)     {         Console.WriteLine(fruit);     }          /*          This code produces the following output:           apple          banana          mango         */ 
like image 27
Scott Whitlock Avatar answered Oct 17 '22 09:10

Scott Whitlock