Home > Software engineering >  How to check if all values of a C# dictionary are true?
How to check if all values of a C# dictionary are true?

Time:11-23

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related