You cannot check an array without iterating through it. So O(n) is the best you get. Another solution would be to control the loading of the array and throw an exception when someone tries to put a value in it that is not 0 or 1 . Another solution might be to use bool[] , which has only two possible values ββanyway, but will require some conversion if you really need numbers. (Note: if you need more than two values, it might make sense to take a look at enum , especially if those values ββshould represent something)
In addition, Where not the best solution here, because you are forced to check the entire array (without early exit). Instead, use Any (but it still does basically what your for loop does - the best case is O(1) , worse than O(n) average O(n) ).
if (myArray.Any(a => a != 0 && a != 1)) {
source share