use*_*239 4 c# arrays byte list
我有以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
我希望list3只包含list2中但不在list1中的byte []数组(标记为"this array"的数组),而是只返回list2的全部内容.那么我尝试了以下内容:
List<byte[]> list3 = new List<byte[]>();
foreach (byte[] array in list2)
if (!list1.Contains(array))
list3.Add(array);
Run Code Online (Sandbox Code Playgroud)
但这让我得到了同样的结果.我究竟做错了什么?
无论Except和Contains调用对象的Equals方法.但是,对于数组,Equals只需执行引用相等性检查.要比较内容,请使用SequenceEqual扩展方法.
您必须在循环中更改支票:
List<byte[]> list3 = new List<byte[]>();
foreach (byte[] array in list2)
if (!list1.Any(a => a.SequenceEqual(array)))
list3.Add(array);
Run Code Online (Sandbox Code Playgroud)