In C# if I have a List of type bool. What is the fastest way to determine if the list contains a true value? I don’t need to know how many or where the true value is. I just need to know if one exists. I will be searching many extremely large lists.
Just use bool trueInList = list.Contains(true);
. This loops the list until there's a true
.
Why do you need something faster with such a simple use-case?
Use either list.Contains(true) or list.Any(true). For a normal list both have complexity O(n). Since Any() is an extension method though, which needs to invoke delegates, the Contains() might still be a bit faster. But to be sure I would simply test both with a large collection.
You could use Any().
list.Any(b => b);
Try this:
var result = myBoolList.Any(i => i==true);
You use the Any(...)
list.Any(c => c == true);
or just
list.Any(c => c);
You can use BinarySearch method of the list.
if(list.BinarySearch(true) > 0){...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With