Bool list check if every item in list is false

后端 未结 4 680
轮回少年
轮回少年 2020-12-18 18:28

I have a List with lots of values. What is the most efficient way to check if every single item in the list equals false?

4条回答
  •  猫巷女王i
    2020-12-18 18:52

    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.

提交回复
热议问题