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

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

    This may be late, but an extension that works for value and reference types alike based on Eric's answer:

    public static partial class Extensions
    {
        public static Nullable Unanimous(this IEnumerable> sequence, Nullable other, IEqualityComparer comparer = null)  where T : struct, IComparable
        {
            object first = null;
            foreach(var item in sequence)
            {
                if (first == null)
                    first = item;
                else if (comparer != null && !comparer.Equals(first, item))
                    return other;
                else if (!first.Equals(item))
                    return other;
            }
            return (Nullable)first ?? other;
        }
    
        public static T Unanimous(this IEnumerable sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
        {
            object first = null;
            foreach(var item in sequence)
            {
                if (first == null)
                    first = item;
                else if (comparer != null && !comparer.Equals(first, item))
                    return other;
                else if (!first.Equals(item))
                    return other;
            }
            return (T)first ?? other;
        }
    }
    

提交回复
热议问题