按位操作到List <bool>

Dr.*_*ail 6 c# linq list

我有一个List<bool>想要按位XOR列表(创建校验位)

这就是我目前所拥有的

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];
}
Run Code Online (Sandbox Code Playgroud)

问:有没有一个Linq单线来解决这个更优雅?

Buh*_*ica 11

bool bResult = bList.Aggregate((a, b) => a ^ b);
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 7

另一个解决方案(除了Buh Buh之外):

bool bResult = bList.Count(a => a) % 2 == 1;
Run Code Online (Sandbox Code Playgroud)

当你xor你的序列bool实际上想要返回,true如果序列中有奇数trues

  • @berkser:是的`Aggregate`更容易阅读,但是`Count`如果在你没有`Aggregate`模拟时经常有用,例如在SQL中 (2认同)