Reputation: 2050
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
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
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 true
s in the sequence
Upvotes: 7
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