Elegantly determine if more than one boolean is “true”

前端 未结 22 1072
深忆病人
深忆病人 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: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)
    

提交回复
热议问题