How to compare two arrays of bytes [duplicate]

2019-03-17 09:28发布

问题:

This question already has an answer here:

  • Comparing two byte arrays in .NET 28 answers

I have two byte arrays with the exact same content. I tried:

if (bytearray1 == bytearray2) {...} else {...}

and

if (Array.Equals(bytearray1, bytearray2)) {....} else {...}

All time it goes to the else! I don't know why! I checked both arrays manually several times!!!

回答1:

Try using the SequenceEqual extension method. For example:

byte[] a1 = new byte[] { 1, 2, 3 };
byte[] a2 = new byte[] { 1, 2, 3 };
bool areEqual = a1.SequenceEqual(a2); // true


回答2:

The == operator compares by reference; those are two different instances.

Array.Equals is really Object.Equals, which calls the instances Equals method.
Since arrays do not override Equals(), this too compares by reference.

Instead, you should call the LINQ SequenceEqual() method.



回答3:

Both the == operator and the Equals method will test reference equality. Since you have two separate arrays, they will never be equal.

Since you want to test that both arrays have the same content in the same order, try using the SequenceEqual method instead.



回答4:

As an alternative, if you are not comfortable using LINQ you can use the System.Convert class...

byte[] a1;
byte[] a2;

if (System.Convert.ToBase64String(a1) == System.Convert.ToBase64String(a2)) {
    doSomething();
}
else {
    doSomethingElse();
}


标签: c# bytearray