Randomman159 Randomman159 - 2 months ago 7
C# Question

adding booleans (as integer)

I wrote a code in AS3 which allowed me to check if a particular number of things were true...

If (true + false + true + true + false + true + true < 4)
{

}


When i tried rewriting in C#, it tells me i cannot add type bool and bool. Is the best way of doing this to rewrite it like this? Or is there some simpler work around?

If ((true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) + (false?1:0) + (true?1:0) + (true?1:0) < 4)
{

}

Answer

Try using IEnumerable<T>.Count(Func<T,bool>) from System.Linq, with T as bool, on a params method parameter.

public static int CountTrue(params bool[] args)
{
   return args.Count(t => t);
}

Usage

// The count will be 3
int count = CountTrue(false, true, false, true, true);

You can also introduce a this extension method:

public static int TrueCount(this bool[] array)
{
   return array.Count(t => t);
}

Usage

// The count will be 3
int count = new bool[] { false, true, false, true, true }.TrueCount();