I have
var previous = new BitArray(new bool[]{true});
var current = new BitArray(new bool[]{false});
I want to concatenate them. I have already tried:
var next = new BitArray(previous.Count + current.Count);
var index = 0;
for(;index < previous.Count; index++)
next[index] = previous[index];
var j = 0;
for(;index < next.Count; index++, j++)
next[index] = current[j];
previous = current;
But it doesn't look like the best way to do it.
Unfortunately it looks like your method might be as good as it gets - if BitArray implemented IEnumerable<T> (instead of just IEnumerable) then we could use LINQ extension methods to make it a bit prettier.
If I were you, I'd wrap this up into an extension method on BitArray:
public static BitArray Prepend(this BitArray current, BitArray before) {
var bools = new bool[current.Count + before.Count];
before.CopyTo(bools, 0);
current.CopyTo(bools, before.Count);
return new BitArray(bools);
}
public static BitArray Append(this BitArray current, BitArray after) {
var bools = new bool[current.Count + after.Count];
current.CopyTo(bools, 0);
after.CopyTo(bools, current.Count);
return new BitArray(bools);
}
One can do this with LINQ, after Cast<bool>()
the bitarray 'becomes' IEnumerable<bool>
:
var previous = new BitArray(new bool[] { true });
var current = new BitArray(new bool[] { false });
BitArray newBitArray =
new BitArray(previous.Cast<bool>().Concat(current.Cast<bool>()).ToArray());
I don't think this LINQ method will be fast.
The framework doesn't provide a nice way of doing this. You could create an array of bools that is large enough to store both BitArrays. Then use BitArray.CopyTo to copy each BitArray in the array of bools (you can specify where to start inserting the elements).
After this is done, create another BitArray with the constructor that accepts an array of bools.
A lot of work I know, but there doesn't seem to be another way. It's less code than your current method however.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With