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

后端 未结 9 580
孤城傲影
孤城傲影 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:35

    return collection.All(i => i == collection.First())) 
        ? collection.First() : otherValue;.
    

    Or if you're worried about executing First() for each element (which could be a valid performance concern):

    var first = collection.First();
    return collection.All(i => i == first) ? first : otherValue;
    

提交回复
热议问题