using System.Collections.Generic;
using System.Linq;
namespace Vanara.Collections
{
///
/// Checks the linear equality of two enumerated lists. For lists to be equal, they must have the same number of elements and each index
/// must hold the same value in each list.
///
/// The element type in the list.
public sealed class EnumerableEqualityComparer : IEqualityComparer>
{
private static readonly EqualityComparer elementComparer = EqualityComparer.Default;
/// Determines whether the specified lists are equal.
/// The first list of type T to compare.
/// The second list of type T to compare.
/// if the two lists are equal; otherwise.
public bool Equals(IEnumerable first, IEnumerable second)
{
if (ReferenceEquals(first, second))
return true;
if (first is null || second is null)
return false;
var e1 = first.GetEnumerator();
var e2 = second.GetEnumerator();
bool move1, move2 = false;
while ((move1 = e1.MoveNext()) && (move2 = e2.MoveNext()))
{
if (!elementComparer.Equals(e1.Current, e2.Current))
return false;
}
return move1 == move2;
}
/// Returns a hash code for the specified object.
/// The Object for which a hash code is to be returned.
/// A hash code for the specified object.
public int GetHashCode(IEnumerable list)
{
unchecked
{
return list is null ? 0 : list.Aggregate(17, (s, e) => s * 31 + elementComparer.GetHashCode(e));
}
}
}
}