1

I have an array of int array. I want to check if one int array exist in the collection

        var coll = new int[3][]
        {
            new[] {5, 5},
            new[] {4, 2},
            new[] {3, 4}
        };
        var valueToCheck = new int[] {4, 2};

        if (coll.Contains(valueToCheck))
        {
            // My logic
        }

but coll.Contains(valueToCheck) is returning false. Can someone suggest what am i doing wrong here?

1
  • 4
    The reason this returns false is because your valueToCheck is a different object instance than your original array of {4, 2}. Despite the fact that the int values inside the arrays are equal, the arrays themselves are not because you are asking whether that instance of your valueToCheck array is contained by coll. It is not. Commented Jun 3, 2019 at 10:14

1 Answer 1

6

You can use Any combined with SequenceEquals. This will ensure that only the correct sequence is matched.

if (coll.Any(o => o.SequenceEqual(valueToCheck))) {
    // it exists!
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is probably the best/easiest way. But performance might be an issue with large arrays (of large arrays).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.