在C#中,要比较两个数组是否完全相同(这两个数组的对应位置都是相同的,不用排序),除了循环每个元素都比较之外,还有其他更好的办法吗。
谢谢

解决方案 »

  1.   

    http://topic.csdn.net/u/20091219/21/01c19e66-cc1f-4e5b-a681-50fea5dbad0d.html
      

  2.   

    可以使用内存比较的API RtlCompareMemory返回值表示有多少个字节相同
    [DllImport("ntdll.dll")]
    public static extern int RtlCompareMemory(IntPtr Destination, 
        IntPtr Source, int Length);private void Form1_Load(object sender, EventArgs e)
    {
        var a = new int[] { 1, 2, 3, 4, 5, 6 };
        var b = new int[] { 1, 2, 3, 4, 5, 6 };
        var c = new int[] { 1, 2, 3, 4, 5, 7 };
        MessageBox.Show("" + (RtlCompareMemory(Marshal.UnsafeAddrOfPinnedArrayElement(a, 0),
            Marshal.UnsafeAddrOfPinnedArrayElement(b, 0), sizeof(int) * a.Length) == sizeof(int) * a.Length));    MessageBox.Show("" + (RtlCompareMemory(Marshal.UnsafeAddrOfPinnedArrayElement(a, 0),
            Marshal.UnsafeAddrOfPinnedArrayElement(c, 0), sizeof(int) * a.Length) == sizeof(int) * a.Length));
    }
    Marshal.UnsafeAddrOfPinnedArrayElement获取数组某个元素的内存地址。
      

  3.   

    sealed class Comparer<T>
    {
    public static int Compare(T obj1, T obj2, int n)
    {
    int size = n;
    long l1, l2;
    for (int i = 0; i < size / 8; i++)
    {
    l1 = Marshal.ReadInt64(obj1, i * 8);
    l2 = Marshal.ReadInt64(obj2, i * 8);
    if (l1 < l2)
    return -1;
    if (l1 > l2)
    return 1;
    }
    for (int i = size - size % 8; i < size; i++)
    {
    l1 = Marshal.ReadByte(obj1, i * 8);
    l2 = Marshal.ReadByte(obj2, i * 8);
    if (l1 < l2)
    return -1;
    if (l1 > l2)
    return 1;
    }
    return 0;
    }
    }int[] a = new int[] { 1, 3, 4, 4 };
    int[] b = new int[] { 1, 3, 4, 5 };int ret = Comparer<int[]>.Compare(a, b, a.Length * sizeof(int)); //ret为0时表示数组相等