Reputation: 16339
How to check the array true_or_false
containing a value of 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;
}
Upvotes: 10
Views: 20146
Reputation: 283624
If they are not all true, then at least one is false.
Therefore:
!true_or_false.All(x => x)
Docu: http://msdn.microsoft.com/en-us/library/bb548541.aspx
EDIT: .NET 2.0 version, as requested:
!Array.TrueForAll(true_or_false, delegate (bool x) { return x; })
or
Array.Exists(true_or_false, delegate (bool x) { return !x; })
NOTE: I've been staying away from the nonsensical code that sets true_or_false
, but it could be that what you want is:
int emptyBox = Array.FindIndex(txtbox_and_message, string.IsNullOrEmpty);
which will give you -1 if all the strings are non-empty, or the index of the failing string otherwise.
Upvotes: 17
Reputation: 100322
If on .NET3.5+ you can use System.Linq
, and then check using Any
:
// if it contains any false element it will return true
true_or_false.Any(x => !x); // !false == true
If you can't use Linq, then you have other choises:
Using Array.Exists
static method: (as Ben mentioned)
Array.Exists(true_or_false, x => !x);
Using List.Exists
(you would have to convert the array to a list to access this method)
true_or_falseList.Exists(x => !x);
Or you will need to iterate through 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
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]);
}
Upvotes: 1
Reputation: 18498
There are a couple of solutions:
Solution 1: do a for loop after that for loop to check if the true_or_false contains false like this:
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);
PK
Upvotes: 2
Reputation: 5880
Intead of your code:
bool containsEmptyText = txtbox_and_message.Contains( t => t.Text ==String.Empty)
Upvotes: 2