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

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

    An alternative to using LINQ:

    var set = new HashSet<int>(values);
    return (1 == set.Count) ? values.First() : otherValue;
    

    I have found using HashSet<T> is quicker for lists of up to ~ 6,000 integers compared with:

    var value1 = items.First();
    return values.All(v => v == value1) ? value1: otherValue;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-02 11:37

    Good quick test for all equal:

    collection.Distinct().Count() == 1
    
    0 讨论(0)
提交回复
热议问题