Check if array contains false?

How to check true_or_false array containing false?

 bool[] true_or_false = new bool[10]; for (int i = 0; i < txtbox_and_message.Length; i++) { bool bStatus = true; if (txtbox_and_message[i] == "") { bStatus = false; } true_or_false[i] = bStatus; } 
+6
contains arrays c #
source share
6 answers

If they are not all true, then at least one of them is false.

Thus:

 !true_or_false.All(x => x) 

Docu: http://msdn.microsoft.com/en-us/library/bb548541.aspx

EDIT: .NET 2.0 version, upon request:

 !Array.TrueForAll(true_or_false, delegate (bool x) { return x; }) 

or

 Array.Exists(true_or_false, delegate (bool x) { return !x; }) 

NOTE. I stayed away from pointless code that sets true_or_false , but maybe that you want:

 int emptyBox = Array.FindIndex(txtbox_and_message, string.IsNullOrEmpty); 

which will give you -1 if all lines are not empty or a pointer to a failed line otherwise.

+15
source share
 return true_or_false.Any(p => !p); 
+11
source share
 using System.Linq; 

then

 true_or_false.Contains(false); 
+8
source share

Your code interactivity:

 bool containsEmptyText = txtbox_and_message.Contains( t => t.Text ==String.Empty) 
+2
source share

There are several solutions:

Solution 1: do a for loop after that for the loop to check if true_or_false contains false:

if you want to achieve this without fancy tricks, and you want to program the code yourself, you can do this:

 bool containsFalse = false; for(int j = 0; j < true_or_false.Length; j++) { //if the current element the array is equals to false, then containsFalse is true, //then exit for loop if(true_or_false[j] == false){ containsFalse = true; break; } } if(containsFalse) { //your true_or_false array contains a false then. } 

Solution 2:

 !true_or_false.All(x => x); 

PC

+2
source share

If on .NET3.5 + you can use System.Linq , then check Any :

 // if it contains any false element it will return true true_or_false.Any(x => !x); // !false == true 

If you cannot use Linq, you have other options:

Using the static method Array.Exists : (as Ben mentioned)

 Array.Exists(true_or_false, x => !x); 

Using List.Exists (you will need to convert the array to a list to access this method)

 true_or_falseList.Exists(x => !x); 

Or you will need to iterate over the array.

 foreach (bool b in true_or_false) { if (!b) return true; // if b is false return true (it contains a 'false' element) } return false; // didn't find a 'false' element 

Related

  • Linq. Any VS.Exists

And optimizing your code:

 bool[] true_or_false = new bool[10]; for (int i = 0; i < txtbox_and_message.Length; i++) { true_or_false[i] = !String.IsNullOrEmpty(txtbox_and_message[i]); } 
+1
source share

All Articles