Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an opposite of LINQ's All method?

Tags:

c#

linq

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.

like image 846
TankorSmash Avatar asked Jan 20 '13 06:01

TankorSmash


2 Answers

All() checks that a given Predicate returns true for all items. In terms of framework development, it wouldn't make any sense to write a seperate method that checks that a given Predicate returns false for all items, as it is so easy to "not" a predicate. However, you can write your own extension method:

public static bool None<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    return !source.Any(predicate);
}
like image 152
Eren Ersönmez Avatar answered Sep 18 '22 06:09

Eren Ersönmez


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.

like image 40
JLRishe Avatar answered Sep 18 '22 06:09

JLRishe