I need to check that an int[] contains only certain values (in this case 0s & 1s) and throw an exception if it doesn't.
Is there a more efficient way to do it than either of the following solutions?
Simple (but O(n)):
for(int n = 0; n < myArray.Length; n++)
if(!(myArray[n] == 0 || myArray[n] == 1))
throw new Exception("Array contains invalid values");
Using Where():
if(myArray.Where(n => !(n==1 || n==0)).ToArray().Length > 0)
throw new Exception("Array contains invalid values");
for
loop is the best you can get. Looks like you think LINQ can do "magic" because you didn't say O(N) for the "using Where()" – Kidding