如何使用Contains()
,但数组是比较对象?这里的区别在于我需要检查数组内容的相等性,而不是内存地址。我怎么能这样做?
var array = List<byte[]>();
var searchFor = new byte[23]; //has some value in it
array.Contains(searchFor); //Doesn't work properly
答案 0 :(得分:3)
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));
答案 1 :(得分:0)
要添加到所选答案,这也是可能的
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;