Officially ForEach
is not a LINQ statement. It usually only works for Lists.
From your code I assume that you want to throw an exception if any of the Foo
objects in MyList
has a false IsRequired
value.
You statement would be:
if (MyList.Any(foo => !foo.IsRequired))
throw new Exception();
In words: if any of the foo elements in MyList
has a false IsRequired value, throw a new Exception
The nice thing from using Any instead of first creating a list before checking, is that if you have an IEnumerable, and one of the first elements in the list would throw an exception, the rest of your list would not have been created in vain. See StackOverflow: What are the benefits of deferred execution?
Later you wrote:
The problem is that I want to find all Foo elements in myList which
are not required. It's seems not possible with the Any method, it will
fail on the first one.
If you want to find all Foo elements in the list that are not required, you still can use Linq, using Enumerable.Where:
var notRequiredFoos = myList
.Where(elementInList => !elementInList.IsRequired);
usage:
foreach (var notRequiredFoo in notRequiredFoos)
{
Console.WriteLine($"Foo element {notRequiredFoo.ToString} is not required");
}
Or if you want to throw an exception as soon as you found one, Linq will still help you: Enumerable.FirstOrDefault
var notRequiredFoo= myList
.Where(elementInList => !elementInList.IsRequired);
.FirstOrDefault();
if (notRequiredFoo != null)
{ // we found a Foo that is not required
throw new MyException(notRequiredFoo);
}
// else: all Foos are required
Again, you still don't have to check all elements in the list, it will stop as soon as one is found.