Cómo probar de manera más eficiente si dos matrices contienen elementos equivalentes en C #
Tengo dos matrices y quiero saber si contienen los mismos elementos. @Equals(object obj)
no funciona porque una matriz es un tipo de referencia. He publicado mi intento a continuación, pero como estoy seguro de que esta es una tarea común, me gustaría saber si hay una mejor prueba.
public bool ContainsEquivalentSequence<T>(T[] array1, T[] array2)
{
bool a1IsNullOrEmpty = ReferenceEquals(array1, null) || array1.Length == 0;
bool a2IsNullOrEmpty = ReferenceEquals(array2, null) || array2.Length == 0;
if (a1IsNullOrEmpty) return a2IsNullOrEmpty;
if (a2IsNullOrEmpty || array1.Length != array2.Length) return false;
for (int i = 0; i < array1.Length; i++)
if (!Equals(array1[i], array2[i]))
return false;
return true;
}
Update - System.Linq.Enumerable.SequenceEqual no es mejorReflexioné la fuente y no compara la longitud antes de ejecutar el bucle. Esto tiene sentido ya que el método está diseñado generalmente para unaIEnumerable<T>
, no para unT[]
.
public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
if (comparer == null)
{
comparer = EqualityComparer<TSource>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
using (IEnumerator<TSource> enumerator = first.GetEnumerator())
{
using (IEnumerator<TSource> enumerator2 = second.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (!enumerator2.MoveNext() || !comparer.Equals(enumerator.Current, enumerator2.Current))
{
return false;
}
}
if (enumerator2.MoveNext())
{
return false;
}
}
}
return true;
}