Zdravko Boyanov
Zdravko Boyanov

Reputation: 49

How to invert boolean array?

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

Answers (2)

Behemoth
Behemoth

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

ProgrammingLlama
ProgrammingLlama

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

Related Questions