The implementation of SequenceEqual
is kind of similar::
using (IEnumerator<TSource> enumerator1 = first.GetEnumerator())
using (IEnumerator<TSource> enumerator2 = second.GetEnumerator())
{
while (enumerator1.MoveNext())
{
if (!enumerator2.MoveNext() || !comparer.Equals(enumerator1.Current, enumerator2.Current))
{
return false;
}
}
if (enumerator2.MoveNext())
{
return false;
}
}
return true;
This default SequenceEqual
method use default EqualityComparer<int>.Default
for int
which is value equality.
Array
implement IStructuralEquatable
with Equal
method:
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
{
if (other == null) return false;
if (!object.ReferenceEquals(this, other))
{
Array array = other as Array;
if ((array == null) || (array.Length != this.Length))
{
return false;
}
for (int i = 0; i < array.Length; i++)
{
object x = this.GetValue(i);
object y = array.GetValue(i);
if (!comparer.Equals(x, y))
{
return false;
}
}
}
return true;
}
The IEqualityComparer
from input parameter is used, in here you input StructruralEqualityComparer
but int
does not implement IStructruralEquatable
, so it uses default comparer for int
which is value equality.
But, needless to input StructruralEqualityComparer
because int
is not structural, you should just use:
(arr1 as IStructuralEquatable).Equals(arr2, EqualityComparer<int>.Default);
It still works. You should use StructruralEqualityComparer
if item in array is structrural
So to sum up, the implementation for both is kind of the same, both iterate two array based on value equality of int
to make comparison.
I would prefer the LINQ verson since it is more readable.