Elegantly determine if more than one boolean is “true”

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

    While I like LINQ, there are some holes in it, like this problem.

    Doing a count is fine in general, but can become an issue when the items your counting take a while to calculate/retrieve.

    The Any() extension method is fine if you just want to check for any, but if you want to check for at least there's no built in function that will do it and be lazy.

    In the end, I wrote a function to return true if there are at least a certain number of items in the list.

    public static bool AtLeast(this IEnumerable source, int number)
    {
        if (source == null)
            throw new ArgumentNullException("source");
    
        int count = 0;
        using (IEnumerator data = source.GetEnumerator())
            while (count < number && data.MoveNext())
            {
                count++;
            }
        return count == number;
    }
    

    To use:

    var query = bools.Where(b => b).AtLeast(2);
    

    This has the benefit of not needing to evaluate all the items before returning a result.

    [Plug] My project, NExtension contains AtLeast, AtMost and overrides that allow you to mix in the predicate with the AtLeast/Most check. [/Plug]

提交回复
热议问题