I have a List<bool>
with lots of values. What is the most efficient way to check if every single item in the list equals false
?
4 Answers
You can use Enumerable.Any
it will find satisfy the condition on first match. As Habib rightly said better to use Any as Enumerable.All would return true for an Empty list of bool.
!lst.Any(c=> c == true);
OR use Enumerable.All
lst.All(c=> c == false);
-
6+1, Better to use
Any
, sinceEnumerable.All
would returntrue
for an Empty list of bool.– HabibMar 24, 2014 at 19:06 -
+1 This performs better than All(), because it does always iterates the whole list; it stops when it find one Mar 24, 2014 at 19:06
-
1@AdrianCarneiro Uhm ..? That is not making sense to me. Both are lazy and require looking at the same number of elements in this case. Mar 24, 2014 at 19:07
-
1@user2864740, negated is just a short way of providing
Any
with the bool value, Consider the following code:List<bool> list = new List<bool>(); var b1 = list.All(r => r == false); var b2 = list.Any(r => r == false);
, nowb1
would betrue
andb2
would be false. It is just thatEnumerable.All
behaves differently on an empty list.– HabibMar 24, 2014 at 19:14 -
1obviously the list contains some items.and these two statement are not the same.First return
true
if there is any item that equals totrue
Second return true if all item's equals tofalse
.You need a negation operator on first statement. Mar 24, 2014 at 19:20
A significantly faster solution, not mentioned here, is using Contains
if (!myList.Contains(true))
// Great success - all values false!
I have compared Contains
against IEnumerable.Any
and Contains
returns faster. In my tests IEnumerable.All
performed the same as IEnumerable.Any
, perhaps a similar algorithm is used for both these functions under the hood. I also checked IEnumerable.Exists
which performed better than IEnumerable.Any
and IEnumerable.All
, but was still slower than Contains
.
Of a list of 10,000,000 bool entries (I also tried 0 and 1 entries, with similar results), I came up with the following metrics:
Elapsed via Any = 95ms
Elapsed via All = 88ms
Elapsed via Exists = 27ms
Elapsed via Contains = 17ms
Contains is ~5.59x faster than Any!
Tested with the following code:
// setup initial vars
var myList = new List<bool>();
for (int x = 0; x < 10000000; x++)
myList.Add(false);
var containsAllFalse = false;
Stopwatch sw = new Stopwatch();
// start test
sw.Start();
containsAllFalse = !myList.Any(x => x);
sw.Stop();
// get result for Any
var timeAny = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 2
sw.Restart();
containsAllFalse = myList.All(x => x == false);
sw.Stop();
// get result for All
var timeAll = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 3
sw.Restart();
containsAllFalse = !myList.Exists(x => x == true);
sw.Stop();
// get result for All
var timeExists = sw.ElapsedMilliseconds;
// reset variable state (just in case it affects anything)
containsAllFalse = false;
// start test 4
sw.Restart();
containsAllFalse = !myList.Contains(true);
sw.Stop();
// get result from Contains
var timeContains = sw.ElapsedMilliseconds;
// print results
var percentFaster = Math.Round((double)timeAny / timeContains, 2);
Console.WriteLine("Elapsed via Any = {0}ms", timeAny);
Console.WriteLine("Elapsed via All = {0}ms", timeAll);
Console.WriteLine("Elapsed via Exists = {0}ms", timeExists);
Console.WriteLine("Elapsed via Contains = {0}ms", timeContains);
Console.WriteLine("Contains is ~{0}x faster than Any!", percentFaster);
Note this will only work with types where type can only have two states (i.e. it won't work variables of >2 states, such as Nullable<bool>
)
-
1Nice performance comparison. Where there are many solutions performance takes priority.– WKaraJul 31, 2018 at 7:54
-
Is there a way to perform this if the list isnt a bool but of a class that contains a boolean value ? Feb 21, 2019 at 13:01
-
1"..as it can return early at the first occurrence of true.." so can (and do) both
All
andAny
. WhileContains
may be faster, it is not faster due to early termination. Check the implementation of in the .NET Reference Source's IEnumerable.All which, as I would expect, is lazy and does not force evaluation of the entire sequence. Feb 21, 2019 at 16:37 -
@user2864740 great point - thank you! I'll edit the OP to reflect this. Feb 22, 2019 at 2:21
I agree with the use of IEnumerable.Any/All. However, I disagree with the currently most-voted answer (which was wrong at the time of writing this) and several of the associated comments of Any vs All.
These following operations are equivalent semantically. Note that the negations are applied both inside, on the predicate, and on the result of the operation.
!l.Any(x => f(x))
l.All(x => !f(x))
Now, in this case we are thus looking for:
If it is not the case that there is any true value.
!l.Any(x => x) // f(x) = x == true
Or,
It is the case that every value is not true.
l.All(x => !x) // f'(x) = !f(x) = !(x == true)
There is nothing special for empty lists the result is the same: e.g. !empty.Any(..)
is false, as is empty.All(..)
and the above equivalence relation remains valid.
In addition, both forms are lazily evaluated and require the same number of evaluations in LINQ To Objects; internally the difference, for a sequence implementation, is merely negating the check on the predicate and the result value.
-
Is there a way to perform this if the list isnt a bool but of a class that contains a boolean value ? Feb 21, 2019 at 12:07
-
@RyanN1220 Yes. LINQ's IEnumerable is flexible in this aspect as a function is accepted in many contexts (there are restrictions for certain providers such a LINQ-to-EF, eg.). The
All/Any
functions take an optionalFunc<T, bool>
. In the above,f(x)
is a "some code" (and/or a function) that accepts x and return a bool. Eg., givenvar a = new [] { Tuple.Create(1, true), Tuple.Create(1, false) }
, thena.Any(x => x.Item2)
is true anda.All(x => x.Item2)
is false. Feb 21, 2019 at 16:32
You can use LINQ's
All
method:
list.All(x => x == false);
This will return false
immediately if it finds a value that equals to true
.
-
Is there a way to perform this if the list isnt a bool but of a class that contains a boolean value ? Feb 21, 2019 at 13:01
-
1@RyanN1220 the lambda variable "x" represents the object here. so all you need is to change the condition
x.SomeBoolProperty == false
or!x.SomeBoolProperty
Feb 21, 2019 at 13:03