'How to check if all values of a C# dictionary are true?

I have a dictionary in C# with

var customDictionary = new Dictionary<string, bool>();

How can I check if all the values in a dictionary are true and return true only in that case?



Solution 1:[1]

var allValuesAreTrue = customDicationary.Values.All(value => value);

Notice that the result is true if the dictionary is empty because "all values" are equal to true.

Solution 2:[2]

One way to do it, is with Linq. Check the values of the dictionary and see how many come back with true/false and continue based on that number.

public void Program()
{
    var customDictionary = new Dictionary<string, bool>();
    customDictionary.Add("Apples are red", true);
    customDictionary.Add("Oranges are green", false);
    customDictionary.Add("Carrots are orange", true);
    
    bool allTrue = CheckDictionary(customDictionary);
    
    if(allTrue == true)
    {
        Console.Write("All True");
    }
    else{
        Console.Write("At least one false");
    }
}

public bool CheckDictionary(Dictionary<string, bool> dictToCheck)
{
    var test = dictToCheck.Where(x => x.Value == false);
    if (test.Count() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Output: At least one false

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Liversage
Solution 2 J33NO