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

后端 未结 9 588
孤城傲影
孤城傲影 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条回答
  •  猫巷女王i
    2020-12-02 11:27

    public int GetResult(List list){
    int first = list.First();
    return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
    }
    

提交回复
热议问题