【问题标题】:How to check if list contains byte array?如何检查列表是否包含字节数组?
【发布时间】:2013-09-30 23:02:46
【问题描述】:

我有字节缓冲区:

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

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

【问题讨论】:

  • 请在您的问题中添加语言标签。 (我假设 C# 但我不确定)

标签: c# arrays design-patterns contains


【解决方案1】:

您当前的版本不工作,因为它会根据 reference 相等性进行检查。

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

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

【讨论】:

    【解决方案2】:
    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-13
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2021-05-18
      相关资源
      最近更新 更多