Say I have the following BitArray combinedResults = searchBitArray.And(genreBitArray);
Which contains positive bits i.e 100100110000
How can I get the开发者_如何学运维 indexes of all the positive ones ?
Here's a first, decidedly ghetto, crack at it:
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i])
pos.Add(i);
}
That would give you a list containing 0, 3, 6, 7. You could start at ba.Length - 1 and decrement down to zero if you need to read from right to left.
edit: Wrapped in an extension method, just because:
void Main()
{
BitArray ba = new BitArray(new bool[] {true,false,false,true,false,false,true,true,false,false,false,false});
List<int> positives = ba.GetBitPositions(true);
List<int> negatives = ba.GetBitPositions(false);
}
public static class BitArrayExtensions
{
public static List<int> GetBitPositions(this BitArray ba, bool MatchCondition)
{
List<int> pos = new List<int>();
for (int i = 0; i < ba.Length; i++)
{
if (ba[i] == MatchCondition)
pos.Add(i);
}
return pos;
}
}
精彩评论