Home > Mobile >  check if a list of array contains an array in c#
check if a list of array contains an array in c#

Time:02-19

I'm working in c# and I have a list of integer arrays and an array. I need to check if the list contains that specific array. The list.Contains(T item) method didn't provide the desired output, so I wrote a custom method

static bool CheckContains( List<int[]> forbiddenChoice, int[] finalChoice)
    {
        for (int i = 0; i < forbiddenChoice.Count; i  )
        {
            if(Array.Equals(forbiddenChoice[i], finalChoice))
            {
                return true;
            }
        }
        return false;
    }

still, this method always returns false even if I pass an array that is included in the list. How to resolve the issue?

CodePudding user response:

Use SequenceEqual method from System.Linq

static bool CheckContains(List<int[]> forbiddenChoice, int[] finalChoice)
{
    for (int i = 0; i < forbiddenChoice.Count; i  )
    {
        if (forbiddenChoice[i].SequenceEqual(finalChoice))
        {
            return true;
        }
    }
    return false;
}

CodePudding user response:

You can use Enumerable.SequenceEqual

if (forbiddenChoice[i].SequenceEqual( finalChoice))
{
    return true;
}

Array.IsEqual would return true just if both variables refer to the same object:

int[] array1 = { 1, 4, 5 };
int[] array5 = { 1, 4, 5 };
bool test02 = array5.Equals(array1); // returns False
array5 = array1;
test02 = array5.Equals(array1); // returns True
  • Related