Search code examples
c#linq

How to 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, 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. When the list is empty it should return the "other" value.

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


Solution

  • var val = yyy.First().Value;
    return yyy.Skip(1).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;