FindAll lambda expression on boolean types

67 views Asked by At

I have an intriguing question. considering this line of code :

List<bool> selectedValues = allValues.FindAll(x => x); 

where allValues is a list of booleans. Why is that FindAll() finds all true values in selectedValues list but not all the false one?

To my knowledge, we are assessing the same value in (x => x). So if you assess False and False (or False goes to False), shouldn't that be true as well?

why is it that if x = true, (x=>x) == true, but if x = false, (x=>x) == false.

my understanding is that :

  1. false equals false (that makes it true)
  2. true equals true (that makes it true as well) Why is it that 1) is not true

I rewrote the same syntax as :

List<bool> selectedHobbies = allHobbies.FindAll(hobby => x.Equals(true)); 

The second one is more understanding to me. But I cannot get a grip on the first syntax. because the second syntax actually checks x with another value

3

There are 3 answers

0
shree.pat18 On

In x => x, you are essentially evaluating the expression x, like you would have done for x.Equals(true). Therefore, it will only pick the values where this expression evaluates to true i.e. all true values in your collection.

0
jmcilhinney On

You don't understand how lambda expressions work so you should do some research on that.

(x => x) is not comparing x to x. The => is not a comparison operator. The first x is simply declaring a variable to refer to the current item in the list, much as you would do in a foreach loop. A lambda that compared x to x would look like this:

(x => x == x)

In that case, you'd get every item in the list because every item is equal to itself. That lambda is evaluating the Boolean expression to the right of the => and filtering based on the result. Items for which that expression evaluates to true will be included and the others will be excluded. That lambda is equivalent to this:

(x => x == true)

If x is true then the expression (which is just x) is true and that item will be included. If x is false then the expression is false and that item will be excluded. In words, this:

allValues.FindAll(x => x)

is saying "find all items in allValues where the expression x for item x is true".

0
Peter Csala On

FindAll acts a filter. It keeps only that elements where the provided Predicate is evaluated to true. Since your source collection contains booleans that's why x => x is enough to act as a Predicate (a function that returns a boolean).

If you would want to filter for the false values then x => !x could be used.