Reputation: 49
Is there a cleaner way to invert boolean array?
var myBoolArray=new bool[]{true, true, true, true, true};
bool[] revertedArray=new bool[5];
for(int i=0;i<myBoolArray.Length;i++)
{
revertedArray[i]=!myBoolArray[i];
}
Atm I'm doing this, but it looks really ugly.
Upvotes: 1
Views: 904
Reputation: 9310
You can use Array.ConvertAll<TInput, TOutput>
which is more performant than LINQ here.
var myBoolArray = new bool[] { true, true, true, true, true };
bool[] invertedArray = Array.ConvertAll(myBoolArray, b => !b);
Upvotes: 0
Reputation: 38767
There's a neater way using LINQ, though that's about the only benefit:
bool[] invertedArray = myBoolArray.Select(b => !b).ToArray();
Upvotes: 2