Why does IEnumerable.Any return True for a False-booleans collection?

I recently needed to check two lists to see if the datatype is the expected type, by the expected index. So I checked every x element in every index i and saved this comparison as boolean, then I called Any to see if there are any booleans where true. However, the following statement always throws an exception.

var values = new object[] {(UInt64) 40, (Boolean) true, (Double) 45.3};
var types = new[] {typeof (UInt64), typeof (Boolean), typeof (Double)};

if (types.Select((x, i) => values[i].GetType() != x).Any())
    throw new Exception();


(I know why, but after a few minutes of debugging I thought this would be a good question).


source to share

4 answers


does not do what you think. Without the lambda expression in Any()

it, it will just check if any element is in the call enumerated to it.

You either want:

types.Select((x, i) => values[i].GetType() != x).Any(x => x)


or maybe

types.Where((x, i) => values[i].GetType() != x).Any()





with no argument, just checks if the sequence contains elements. If you want to know if there is true

, you should use an overload:

bool anyTrue = bools.Any(b => b);





doesn't check what's in your sequence. It searches if there is any element in the sequence. That is, whether you have a sequence of true false values ​​is irrelevant.



You need to use this overload of Any () method. The overload you are using just returns true if the sequence contains stuff, it doesn't care what the values ​​are. To check for booleans and only return them if they are true, your code should be

if (types.Select((x, i) => values[i].GetType() != x).Any(x => x))
    throw new Exception();




All Articles