How do I check if int[] contains only certain numbers?
问题 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"); 回答1: You can