简体   繁体   中英

check if a list of array contains an array in c#

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?

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

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

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