2013-09-25 102 views
2

我有字節的緩衝區:如何檢查列表是否包含字節數組?

byte[] buffer = new byte[3]; 
List<byte[]> list; 

現在我加入:

while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) 
{  
     bool contains = l.Contains<byte[]>(buffer); //This is not working and checking only reference 

     if (!contains)       
     {       
     l.Add(new byte[] buffer[0],buffer[1],buffer[2]});    
     }     
    } 

如何檢查是否列表包含字節數組wchich具有緩衝相同的價值觀?

+0

請語言標記添加到您的問題。 (我假設C#但我不確定) –

回答

5

您當前所使用的版本無法使用,因爲它會根據參考進行檢查。

你想找出是否有任何列表元素包含了相同的字節順序:

bool contains = list.Any(x => x.SequenceEqual(buffer)); 
0
public static bool ContainsSequence(byte[] toSearch, byte[] toFind) { 
    for (var i = 0; i + toFind.Length < toSearch.Length; i++) { 
    var allSame = true; 
    for (var j = 0; j < toFind.Length; j++) { 
     if (toSearch[i + j] != toFind[j]) { 
     allSame = false; 
     break; 
     } 
    } 

    if (allSame) { 
     return true; 
    } 
    } 

    return false; 
}