How to compare two arrays of bytes [duplicate]

2019-03-17 08:50发布

This question already has an answer here:

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!!!

标签: c# bytearray
4条回答
Lonely孤独者°
2楼-- · 2019-03-17 09:23

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.

查看更多
Summer. ? 凉城
3楼-- · 2019-03-17 09:25

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楼-- · 2019-03-17 09:33

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
查看更多
啃猪蹄的小仙女
5楼-- · 2019-03-17 09:47

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();
}
查看更多
登录 后发表回答