如何比较两个数组列表?

4

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);

我希望 list3 只包含在 list2 中但不在 list1 中(标为“this array”的数组)的byte[] 数组,但它只返回 list2 中的所有内容。然后我尝试了以下方法:

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

但这样做我得到了相同的结果。我错在哪里了?
3个回答

8
ExceptContains都会调用对象的Equals方法。但对于数组,Equals只是执行引用相等性检查。如果要比较内容,请使用SequenceEqual扩展方法。

您需要更改循环中的检查:

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

我猜想它可能是这样的,但是没有找到任何简单的方法可以在不循环遍历每个数组中的每个字节的情况下正确地完成它。非常感谢! - user1067239

0

你的列表只包含一个元素。每个元素都包含一个字节数组,而这些字节数组彼此不同,这就是为什么 Except 和你的实现返回相同结果的原因。

我不是 c# 专家,但你可以尝试定义以下列表:

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

0

使用Equals函数。假设cont_stream是一个字节数组,则

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接