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; }
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.
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.
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.
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.
I found another approach:
foreach (var car in cars) if (!rentedCars.Contains(car)) { // Magic }
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 */
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