如何检查列表是否包含字节数组
本文关键字:包含 是否 字节 字节数 数组 列表 何检查 检查 | 更新日期: 2023-09-27 18:32:48
我有字节缓冲区:
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]});
}
}
如何检查列表是否包含与缓冲区具有相同值的字节数组?
您当前的版本不起作用,因为它基于引用相等性进行检查。
您想了解是否有任何列表元素包含相同的字节序列:
bool contains = list.Any(x => x.SequenceEqual(buffer));
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;
}