the_drow
the_drow

Reputation: 19171

How to check if all of the elements in a list return true for a property using Linq?

I would like to have a LINQ statement that calls the property IsValid.
If all elements returned true, I want the statement to return true as well.
How can it be done?

Upvotes: 8

Views: 11208

Answers (3)

Sharad Shahi
Sharad Shahi

Reputation: 129

You might want to safe guard or be specific. Enumerable.All returns true if the collection is empty

var allValid = myList.Any() && myList.All(item => item.IsValid);

See here Why does Enumerable.All return true for an empty sequence?

Upvotes: 8

jball
jball

Reputation: 25014

You need the Enumerable.All<TSource> method:

bool everythingsZen = anEnumerable.All(a => a.IsValid);

Upvotes: 6

Ben M
Ben M

Reputation: 22492

var allValid = myList.All(item => item.IsValid);

Upvotes: 20

Related Questions