Array.Contains() 按值与数组

本文关键字:数组 Contains Array | 更新日期: 2023-09-27 18:36:59

如何使用Contains(),但数组是比较的对象?这里的区别在于我需要检查数组内容的相等性,而不是内存地址。我该怎么做?

var array = List<byte[]>();
var searchFor = new byte[23]; //has some value in it
array.Contains(searchFor); //Doesn't work properly

Array.Contains() 按值与数组

bool containsArray = array.Any(a => a.SequenceEqual(searchFor));

如果排序对相等无关紧要:

var orderedSearchFor = searchFor.OrderBy(x => x);
bool containsArray = 
      array.Any(a => a.OrderBy(x => x).SequenceEqual(orderedSearchFor));

要添加到所选答案中,这也是可能的

         bool found = (from c in array
                      where c.SequenceEqual(searchFor)
                      select c).Count() > 0;

具体取决于是否要使用类似查询的 LINQ 样式。

这是一个工作示例:

        var array = new List<byte[]>();
        var searchFor = new byte[] { 0xAA, 0xA0 };
        array.Add(searchFor);
         bool found = (from c in array
                      where c.SequenceEqual(searchFor)
                      select c).Count() > 0;