简体   繁体   中英

Array.Contains() by value with arrays

How can I use Contains() , but with arrays being the compared objects? The difference here is that I need to check the equality of the content of the array, not the memory addresses . How can I do this?

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

If ordering does not matter for equality:

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

To add to the selected answer, this is also possible

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

Depending on if you want to use the query like style of LINQ.

Here is a working example:

        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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM