Como testar com mais eficiência se duas matrizes contêm itens equivalentes em C #
Tenho duas matrizes e quero saber se elas contêm os mesmos itens.Equals(object obj)
não funciona porque uma matriz é um tipo de referência. Postei minha tentativa abaixo, mas como tenho certeza de que essa é uma tarefa comum, gostaria de saber se há um teste melhor.
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 não é melhor Eu refleti a fonte e ele não compara o comprimento antes da execução do loop. Isso faz sentido, já que o método é projetado geralmente para umIEnumerable<T>
, não para umT[]
.
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;
}