Ian Ringrose Ian Ringrose - 25 days ago 12
C# Question

Using linq or otherwise, how do check if all list items have the same value and return it, or return an “otherValue” if they don’t?

If all the items in a list have the same value, 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.

see also Neat way to write loop that has special logic for the first item in a collection.

Answer
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.

To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:

if(yyy == null || !yyy.Any()) return otherValue;
Comments