Alex Rivera | Logout

Is there an opposite of LINQ's All method?

Asked 2013-01-20T06:22:44.050
15

I'm currently using

a_list.All(item => !(item.field_is_true == true))

which works well, but I'd like to know if there was a proper LINQ method to do the opposite of all.

Edit
Report

1 Answer

7

The exact opposite of All() is essentially None, but since LINQ has no None() method, you can accomplish the same result through !set.Any().

!a_list.Any(item => item.matches == true)

This will produce true if none of the items in a_list have a matches value that is true.

Another example:

names.All(item => item.StartsWith("R"))

is true if all of the items in names start with R (as you know already).

!names.Any(item => item.StartsWith("R"))

is true if none of the items in names start with R.

Based on your comment below, it sounds like you might just be looking for a way to accomplish the same result as your current code snippet, but in a different way. This should provide the same result as your current code, but without the ! in the predicate:

!a_list.Any(item => item.matches == true)

This can be further simplified to:

!a_list.Any(item => item.matches)

I'd imagine yours could be simplified as well, to this:

a_list.All(item => !item.matches)

There's rarely a good reason to explicitly compare a boolean value with true or false.

answered 2013-01-20T06:24:42.707

Your Answer