title: Counting bits set in a .Net BitArray Class
body: <p>I am implementing a library where I am extensively using the .Net BitArray class and need an equivalent to the Java BitSet.Cardinality() method, i.e. a method which returns the number of bits set. I was thinking of implementing it as an extension method for the BitArray class. The trivial implementation is to iterate and count the bits set (like below), but I wanted a faster implementation as I would be performing thousands of set operations and counting the answer. Is there a faster way than the example below?</p>
  
  <pre><code>count = 0;
  
  for (int i = 0; i &lt; mybitarray.Length; i++)
  {
  
    if (mybitarray [i])
      count++;
  }
  </code></pre>