How to compare two lists of arrays?

I have the following code:

List<byte[]> list1 = new List<byte[]>(); list1.Add(new byte[] { 0x41, 0x41, 0x41, 0x41, 0x78, 0x56, 0x34, 0x12 }); List<byte[]> list2 = new List<byte[]>(); list2.Add(new byte[] { 0x41, 0x41, 0x41, 0x41, 0x78, 0x56, 0x34, 0x12 }); list2.Add(new byte[] { 0x42, 0x42, 0x42, 0x42, 0x78, 0x56, 0x34, 0x12 }); // this array IEnumerable<byte[]> list3 = list2.Except(list1); 

I want list3 to contain only byte [] arrays that are in list2 but not in list1 (the one marked as "this array"), but instead it just returns the whole list2. So, I tried the following:

 List<byte[]> list3 = new List<byte[]>(); foreach (byte[] array in list2) if (!list1.Contains(array)) list3.Add(array); 

but it gave me the same result. What am I doing wrong?

+4
source share
3 answers

Both Except and Contains call the Equals object method. However, for arrays, Equals just does a parity check. To compare content, use the SequenceEqual extension method.

You will need to change your check in your loop:

 List<byte[]> list3 = new List<byte[]>(); foreach (byte[] array in list2) if (!list1.Any(a => a.SequenceEqual(array))) list3.Add(array); 
+8
source

Your lists contain only one item. Each of them contains a byte array, and these byte arrays are different from each other, so Except and your implementation return the same result.

I am not a C # expert, but you can try to define the following lists:

 List<byte> list1 = new List<byte>(); 
0
source

use the Equals function. Suppose cont_stream is a byte array, then

 bool b = cont_stream[1].Equals(cont_stream[2]); 
0
source

Source: https://habr.com/ru/post/1383229/


All Articles