I have a foreach loop that needs to iterate only if the ‘Valid’ property is set to true. Unfortunately if ‘Valid’ is set to false for the first item in the list it exits the entire loop.
Does anyone know the best method for using a condition in a foreach loop? Below is what I have right now.
foreach (var course in agentNewTraining.AllCoursesTaken.TakeWhile(c => c.Valid))
You can use the
Wheremethod.What your code does now is take elements until one which doesn’t match the condition is found. In case the first element of your list, for example, doesn’t match the predicate, you would get an empty collection.