【问题标题】:How to check if all values of a C# dictionary are true?如何检查 C# 字典的所有值是否为真?
【发布时间】:2021-11-22 22:27:07
【问题描述】:

我有一本 C# 字典

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

如何检查字典中的所有值是否都是 true 并仅在这种情况下返回 true?

【问题讨论】:

标签: c# dictionary


【解决方案1】:
var allValuesAreTrue = customDicationary.Values.All(value => value);

请注意,如果字典为空,则结果为 true,因为“所有值”都等于 true

【讨论】:

    【解决方案2】:

    一种方法是使用 Linq。检查字典的值,看看有多少返回真/假,并根据该数字继续。

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

    输出:至少一个错误

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      相关资源
      最近更新 更多