Christian Stewart
Christian Stewart

Reputation: 15519

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

Upvotes: 2

Views: 102

Answers (2)

Serguei Fedorov
Serguei Fedorov

Reputation: 7953

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;

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

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

Upvotes: 3

Related Questions