How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

后端 未结 9 574
孤城傲影
孤城傲影 2020-12-02 10:41

If all the items in a list have the same value, then I need to use that value, otherwise I need to use an “otherValue”. I can’t think of a simple and clear way of doing this

9条回答
  •  离开以前
    2020-12-02 11:14

    Though you certainly can build such a device out of existing sequence operators, I would in this case be inclined to write this one up as a custom sequence operator. Something like:

    // Returns "other" if the list is empty.
    // Returns "other" if the list is non-empty and there are two different elements.
    // Returns the element of the list if it is non-empty and all elements are the same.
    public static int Unanimous(this IEnumerable sequence, int other)
    {
        int? first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (first.Value != item)
                return other;
        }
        return first ?? other;
    }
    

    That's pretty clear, short, covers all the cases, and does not unnecessarily create extra iterations of the sequence.

    Making this into a generic method that works on IEnumerable is left as an exercise. :-)

提交回复
热议问题