Elegantly determine if more than one boolean is “true”

前端 未结 22 1028
深忆病人
深忆病人 2020-12-04 13:40

I have a set of five boolean values. If more than one of these are true I want to excecute a particular function. What is the most elegant way you can think of that would al

相关标签:
22条回答
  • 2020-12-04 14:40

    If there were millions instead of just 5 you could avoid Count()and do this instead ...

    public static bool MoreThanOne (IEnumerable<bool> booleans)
    {
        return booleans.SkipWhile(b => !b).Skip(1).Any(b => b);
    }
    
    0 讨论(0)
  • 2020-12-04 14:40

    I would do something like this, using the params argument.

            public void YourFunction()
            {
                if(AtLeast2AreTrue(b1, b2, b3, b4, b5))
                {
                    // do stuff
                }
            }
    
            private bool AtLeast2AreTrue(params bool[] values)
            {
                int trueCount = 0;
                for(int index = 0; index < values.Length || trueCount >= 2; index++)
                {
                    if(values[index])
                        trueCount++;
                }
    
                return trueCount > 2;
    
            }
    
    0 讨论(0)
  • 2020-12-04 14:40

    I have a much much better one now and very short!

    bool[] bools = { b1, b2, b3, b4, b5 };
    if (bools.Where(x => x).Count() > 1)
    {
       //do stuff
    }
    
    0 讨论(0)
  • 2020-12-04 14:41

    I was going to write the Linq version, but five or so people beat me to it. But I really like the params approach to avoid having to manually new up an array. So I think the best hybrid is, based on rp's answer with the body replace with the obvious Linqness:

    public static int Truth(params bool[] booleans)
    {
        return booleans.Count(b => b);
    }
    

    Beautifully clear to read, and to use:

    if (Truth(m, n, o, p, q) > 2)
    
    0 讨论(0)
  • 2020-12-04 14:41
    if (NumberOfTrue(new List<bool> { bool1, bool2, bool3, bool4 }) >= 2)
    {
        // do stuff
    }
    
    int NumberOfTrue(IEnumerable<bool> bools)
    {
        return bools.Count(b => b);
    }
    
    0 讨论(0)
  • 2020-12-04 14:42

    Not exactly pretty... but here's another way to do it:

    if (
        (a && (b || c || d || e)) ||
        (b && (c || d || e)) ||
        (c && (d || e)) ||
        (d && e)
    )
    
    0 讨论(0)
提交回复
热议问题