tags:

views:

248

answers:

4

In C# and Vb.net,is any way without iterating by loop a bitarray to check contins any true or false value (Dotnet 2.0) ?

+1  A: 

I don't know if you can do it using a BitArray, but if you use an int, long etc. and then check to see if it is greater than 0 (for true) or less than the max value of the data type (for false) that would do it.

so something like this:

bool IsTrue (int bitArray)
{
  return bitArray != 0;
}


bool isFalse (int bitArray)
{
   return bitArray != int.MinValue;
}
Kevin
Indeed, that was going to be my suggestion too assuming it casts ok.
Ian
BitArray is a type. It isn't an `int`.
Mehrdad Afshari
Yeah, but like you said there really isn't a way of checking the values without doing a loop. I was just offering a way of checking an array of bits, not necessarily using the BitArray type.
Kevin
Even in that case, it isn't right. `int` is a signed type. hasFalse should check `!= int.MinValue` and hasTrue should check ` != 0`.
Mehrdad Afshari
Good point, I didn't think that through. Thanks for catching it.
Kevin
+3  A: 

I doubt there's any way you could do it without a loop under the hood (as a BitArray can be arbitrarily long, unlike BitVector32), but if you just don't want to write it yourself:

var hasAnyTrue = input.Cast<bool>().Contains(true);
var hasAnyFalse = input.Cast<bool>().Contains(false);
Mehrdad Afshari
+1  A: 

Indexing into the BitArray and checking the individual boolean values is an obvious solution. If you are concerned about performance, you should first and foremost consider creating your own abstraction, but if you prefer using BitArray for most of your operations, then you could do the check using CopyTo to an int[] of the right size (Count >> 5), and then perform zero or non-zero checks on these ints as appropriate.

jerryjvl
+1  A: 

If you are using the BitArray class from System.Collections you can use the following code to determine if anything is true.

C# version

var anyTrue = myArray.Cast<bool>().Any(x => x);

VB.Net Version

Dim anyTrue = myArray.Cast(Of Boolean)().Any(Function(x) x)
JaredPar
Any advantage in not going with the simpler `.Contains(true)` instead of `Any`? Actually, this is the way I had done that initially, but `Contains` came to mind and I changed it as I couldn't find any specific reason. Ideas?
Mehrdad Afshari