Search code examples
c#linqbooleaniterationternary

LINQ ternary result of binary list


Assume I have a list of binary parameters (in reality it is a list of checkboxes' IsChecked.Value property). I'm trying to get the bool? (ternary) result that:

  • is true if all the elements in the list are true
  • is false if all the elements in the list are false
  • is null in all other cases, thus there are both true and false elements in the list or the list is empty

Until now I came up with the solution that requires iterating over the list twice (checking whether all elements are either true or false) and then comparing the results to deciding whether to return true, false or null.

This is my code:

bool checkTrue = myListOfBooleans.All(l => l);
bool checkFalse = myListOfBooleans.All(l => !l);
bool? result = (!checkTrue && !checkFalse) ? null : (bool?)checkTrue;

How can I achieve it in only one iteration over the list?


Solution

  • You could do that by using Aggegrate

    public bool? AllSameValue(List<bool> myListOfBooleans)
    {
        if(myListOfBooleans.Count == 0) return null; // or whatever value makes sense
    
        return myListOfBooleans.Cast<bool?>().Aggregate((c, a) => c == a ? a : null);
    }
    

    That casts your values to bool? so that you can then compare them and return the value if that they all match or null if there is a difference.

    Of course you could exit early by taking the first one and using All to see if the rest match or not.

    public bool? AllSameValue(List<bool> myListOfBooleans)
    {
        if(myListOfBooleans.Count == 0) return null; // or whatever value makes sense
    
        bool first = myListOfBooleans[0];
        return myListOfBooleans.All(x => x == first ) ? first : null;
    }