5

Possible Duplicate:
Comparing two List<string> for equality

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

I used this, but it does not work, even though 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 !!!!
{
  // 
}
Community
  • 1
  • 1
Ata
  • 12,126
  • 19
  • 63
  • 97

4 Answers4

15

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

Gerard
  • 13,023
  • 14
  • 72
  • 125
Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
9

Have a look at the following on StackOverflow. I believe what you are looking for is the following. Comparing arrays in C#

var arraysAreEqual = Enumerable.SequenceEqual(array1, array2);
Community
  • 1
  • 1
Pieter Germishuys
  • 4,828
  • 1
  • 26
  • 34
3
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;
}
Shahin
  • 12,543
  • 39
  • 127
  • 205
3

You can use the .NET4 feature Array.IStructuralEquatable.Equals like this:

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

This can also be written on one line:

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

Using IStructuralEquatable has the advantage of allowing a custom comparer to be used.

Rick Sladkey
  • 33,988
  • 6
  • 71
  • 95