如何检查列表是否包含字节数组?

时间:2021-05-07 07:30:46

I have byte buffer:

我有字节缓冲区:

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

Now I am adding:

现在我添加:

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

How to check if list contains byte array wchich has the same values as buffer?

如何检查列表是否包含字节数组wchich与缓冲区具有相同的值?

2 个解决方案

#1


5  

Your current version is not working because it does a check based on reference equality.

您的当前版本无法工作,因为它执行基于引用相等的检查。

You want to find out if any list elements contain the same sequence of bytes:

您想知道是否有任何列表元素包含相同的字节序列:

bool contains = list.Any(x => x.SequenceEqual(buffer));

#2


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

#1


5  

Your current version is not working because it does a check based on reference equality.

您的当前版本无法工作,因为它执行基于引用相等的检查。

You want to find out if any list elements contain the same sequence of bytes:

您想知道是否有任何列表元素包含相同的字节序列:

bool contains = list.Any(x => x.SequenceEqual(buffer));

#2


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