简体   繁体   中英

How to compare arrays for equality in C#?

In C++, if you want to check if 2 arrays are equal (in terms of content), you can do:

#include <vector>
#include <cassert>

using namespace std;

int main (int argc, char * const argv[]) {

  vector<int> a;
  a.push_back(5); 
  a.push_back(6);
  a.push_back(7);

  vector<int> b = a;    // this copies array a's contents to array b

  assert( a == b );     // this compares the content of array a and b one element at a time

  return 0;
}

How can I achieve the same thing in C# without writing my own comparison for-loop?

3 links I found so far, though I'm not sure if they are outdated:

I'm a C# newbie and I'm using Mono.

bool equals = array1.OrderBy(a => a).SequenceEqual(array2.OrderBy(a => a));

简单的方法

i am not sure about MOno that's why i deleted my previous answer

you can do it by looping through / Stack implementation becoz push/Pop is O(1) operation and accessing an element in array is also O(1) operation.

If (Arr1.Length != Arr2.Length)
{
    return false // not equals
}
else
  {
     Arr1.Sort(); // important as both array has to be sorted 
     Arr2.Sort() ;// important as both array has to be sorted 

      for(int i=0;i<Arr1.Length ; i++)
         {
           if(Arr[i]!=Arr1[i])
              break;
         }

  }

heres an efficient extension method that should do the trick

public static bool Compare<T>(this T[] source, T[] target, 
       Func<T,T,bool> comparer )
{
    if (source.Length != target.Length)
        return false;
    return !source.Where((t, i) => !comparer(t, target[i])).Any();
}

var a = new[] {2, 3, 4, 5, 6, 7, 8};
var b = new[] {2, 3, 4, 5, 6, 7, 8};
var c = new[] {2, 3, 4, 5, 6, 7, 8, 9};
var d = new[] {2, 4, 3, 5, 6, 8, 7};

var r1 = a.Compare(b, (i1, i2) => i1 == i2); // true
var r2 = a.Compare(c, (i1, i2) => i1 == i2); // false
var r3 = a.Compare(d, (i1, i2) => i1 == i2); // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM