簡體   English   中英

如何比較兩個數組列表?

[英]How do I compare two lists of arrays?

我有以下代碼:

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中的byte []數組(標記為“this array”的數組),而是只返回list2的全部內容。 那么我嘗試了以下內容:

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

但這讓我得到了同樣的結果。 我究竟做錯了什么?

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

您的列表只包含一個元素。 它們中的每一個都包含一個字節數組,並且這些字節數組彼此不同,這就是為什么Except和您的實現返回相同的結果。

我不是ac#expert,但您可以嘗試定義以下列表:

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

使用等於功能。 假設cont_stream是一個字節數組

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM