9

私は持っています

var previous = new BitArray(new bool[]{true});
var current = new BitArray(new bool[]{false});

それらを連結したいと思います。私はすでに試しました:

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;

しかし、それを行うための最良の方法のようには見えません。

4

5 に答える 5

10

残念ながら、あなたのメソッドはそれと同じくらい良いように見えます.BitArrayがIEnumerable <T>を実装した場合(IEnumerableだけではなく)、LINQ拡張メソッドを使用して少しきれいにすることができます.

私があなたなら、これを 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);
}
于 2009-02-05T23:56:38.040 に答える
6

Cast<bool>()bitarray が 'becomes'になった後、LINQ でこれを行うことができます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());

この LINQ メソッドが高速になるとは思いません。

于 2009-03-12T20:27:03.877 に答える
2

フレームワークは、これを行う良い方法を提供していません。両方の BitArray を格納するのに十分な大きさの bool の配列を作成できます。次に、BitArray.CopyTo を使用して、各 BitArray を bool の配列にコピーします (要素の挿入を開始する場所を指定できます)。

これが完了したら、bool の配列を受け入れるコンストラクターで別の BitArray を作成します。

私が知っている仕事はたくさんありますが、別の方法はないようです。ただし、現在の方法よりもコードが少なくなります。

于 2009-02-05T23:56:50.537 に答える
0

これは、ブール値の配列を割り当てなければならないというオーバーヘッドを含まない私の LINQ 実装です。

var result = new BitArray(first.Count + second.Count);

var i = 0;
foreach (var value in first.Cast<bool>().Concat(second.Cast<bool>()))
{
    result[i++] = value;
}
于 2016-03-06T11:20:17.013 に答える
-1

bitarray は内部で int32 を使用するため、bool の代わりに int32 を使用する方が効率的です。

public static BitArray Append(this BitArray current, BitArray after) {
    var ints = new int[(current.Count + after.Count) / 32];
    current.CopyTo(ints, 0);
    after.CopyTo(ints, current.Count / 32);
    return new BitArray(ints);
}

誰かがそれを必要とする場合は、Vb.net で:

<Runtime.CompilerServices.Extension()> _
Public Function Append(ByVal current As BitArray, ByVal after As BitArray) As BitArray
    Dim ints = New Int32((current.Count + after.Count) \ 32 - 1) {}
    current.CopyTo(ints, 0)
    after.CopyTo(ints, current.Count \ 32)
    Return New BitArray(ints)
End Function
于 2013-07-23T15:51:04.407 に答える