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
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;
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;
Good quick test for all equal:
collection.Distinct().Count() == 1