Impostor
Impostor

Reputation: 2050

Bitwise operation to a List<bool>

I have a List<bool> and want to bitwise XOR the list (to create check bits)

here is what I have currently

List<bool> bList = new List<bool>(){true,false,true,true,true,false,false};
bool bResult = bList[0];

for( int i = 1;i< bList.Count;i++)
{
    bResult ^= bList[i];
}

Q: Is there a Linq one-liner to solve this more elegant?

Upvotes: 6

Views: 1784

Answers (4)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

You can use Aggregate:

bool result = bList.Aggregate((res, b) => res ^ b);

This calls the lambda for every element except the first. res is the accumulated value (or the first element for the first call) and b the current value from the list.

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Another one line solution (in addition to Buh Buh's one):

bool bResult = bList.Count(a => a) % 2 == 1;

when you xor a sequence of bool you actually want to return true if there're odd number of trues in the sequence

Upvotes: 7

Buh Buh
Buh Buh

Reputation: 7545

bool bResult = bList.Aggregate((a, b) => a ^ b);

Upvotes: 10

vinnie feng
vinnie feng

Reputation: 9

         List<bool> bList = new List<bool>() { true, false, true, true, true, false, false };
        bool bResult = bList[0];

        //for (int i = 1; i < bList.Count; i++)
        //{
        //    bResult ^= bList[i];
        //}
        bList.ForEach(t=>bResult ^= t);

Upvotes: 0

Related Questions