How to determine if two string arrays correspond to others

Possible duplicate:
Comparing two List <string> for equality

How can I find out if two string arrays are equal to each other?

I used this, but it does not work, although the contents of both are the same.

string[] array1 = new string[]{"A" , "B"}

string[] array2 = new string[]{"A" , "B"}

if(array1 == array2)  // it return false !!!!
{
  // 
}
+3
source share
4 answers
static bool ArraysEqual<T>(T[] a1, T[] a2)
{
    if (ReferenceEquals(a1,a2))
        return true;

    if (a1 == null || a2 == null)
        return false;

    if (a1.Length != a2.Length)
        return false;

    EqualityComparer<T> comparer = EqualityComparer<T>.Default;
    for (int i = 0; i < a1.Length; i++)
    {
        if (!comparer.Equals(a1[i], a2[i])) return false;
    }
    return true;
}
+2
source

If you have access to Linq, use SequenceEqual. Otherwise, just provide the code to first check if the arrays are the same length and then if the elements are equal at each index.

+11
source

StackOverflow. , . #

var arraysAreEqual = Enumerable.SequenceEqual(array1, array2);
+5

.NET4 Array.IStructuralEquatable.Equals :

IStructuralEquatable equ = array1;
bool areEqual = equ.Equals(array2, EqualityComparer<string>.Default);

:

bool areEqual = (array1 as IStructuralEquatable).Equals(array2, EqualityComparer<string>.Default);

Use IStructuralEquatablehas the advantage of allowing the use of a custom resolver.

+3
source

All Articles