Check if IEnumerable items are equal

Yesterday I wanted to check if all list items are equal to each other and realized their no native method in the framework to perform such comparison, I decided to roll out my own and came up with these two versions. I have made both methods to be an IEnumerable extension methods.

The first version is a short elegant Linq statement which I ended up scrapping due to poor performance (linq compares the IEnumerable in one shot).

public static bool IEnumerableItemsNotEqual<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("Source", "Source cannot be null");
    return source.SelectMany(item => source, (item, other) => new
    { item, other })
         .Where(t => !object.ReferenceEquals(t.item,t.other))
          .Select(t => t).Any();
}

The second version performs much since it returns false the first time it two elements fail the comparison using Object.ReferenceEquals

public static bool AreAllItemsEqual<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("Source", "Source cannot be null");
    using (var enumerator = source.GetEnumerator())
    {
        var buffer = new List<T>();
        while (enumerator.MoveNext())
        {
            if (buffer.Any(item => !ReferenceEquals(item, (enumerator.Current))))
                return false;
            buffer.Add(enumerator.Current);
        }
    }
    return true;
}

Add comment