1

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.

3
  • 1
    new bool[5], How do you know it's length 5? And why is it not based on the myBoolArray.Lenght? Commented Apr 1, 2021 at 7:05
  • 3
    Honestly, a bool[] is the worst possible way to store bit data (at least without getting silly); in this case, an int (or even a byte) would be vastly preferable, but for unknown-possibly-large lengths (rather than "at most 32", "at most 64", etc) there's BitArray, which also has a Not() method; guess what Not() does! Commented Apr 1, 2021 at 7:19
  • Eh... this was just an simple example compared to the real code. Commented Apr 1, 2021 at 10:54

2 Answers 2

2

There's a neater way using LINQ, though that's about the only benefit:

bool[] invertedArray = myBoolArray.Select(b => !b).ToArray();
Sign up to request clarification or add additional context in comments.

4 Comments

@SomeBody It seems that OP wants a new array.
But that allocates new array in memory to do something that can be done in place.
@LukaszNowakowski But did OP want to do it in place? It's not going to always be the case that you want to mutate the input. In OP's question they had two arrays at the end. I sense people are getting here from another question that was clear about not wanting a new array.
I noticed that right after I sent my reply. But also take into account that bit from his comment "Eh... this was just an simple example compared to the real code". But you're right I stand corrected. Although I wasn't redirected from question you mentioned :-)
0

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);

6 Comments

It is not more performant than LINQ. ProgrammingLlama's answer is equally performant. Since myBoolArray is an array then LINQ's Select operator returns an IIListProvider<bool> which will preallocate an array on ToArray().
Please just take a look at this benchmark. Linq is indeed slightly slower. Or what am I missing here?
That's not a very good benchmark. Here's a better one. It's far more stable. dotnetfiddle.net/RnNaac
It does show that ConvertAll is faster.
Try this variation on your benchmark to see why yours was particularly bad. dotnetfiddle.net/fSOUbM
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.