Checking for an array in a list, with “List<int[]>.Contains(new int[] { .. })”, always returns false

◇◆丶佛笑我妖孽 提交于 2021-01-28 07:55:03

问题


I am trying to check if list that consists of int[2] arrays contains certain element.

In short, why this produces false? And how can I check this properly?

List < int[] > ngonPairs = new List<int[]> {new int[2] { 0, 1 }};

bool flag = ngonPairs.Contains(new int[2] { 0, 1 });

Flag is always false.


回答1:


This is because

new[]{1, 2} != new[]{1, 2}

They are different arrays, and changes to one won't be reflected in the other.

However using LINQ's SequenceEqual, you can compare the contents of two sequences:

new[]{1, 2}.SequenceEqual(new[]{1, 2}) // == true

Now, using LINQ's Any you could:

bool flag = ngonPairs.Any(p => p.SequenceEqual(new int[] {0, 1}));

.Any operates over a sequence and returns true if any of the items in the sequence satisfy the predicate.

In this case, the predicate compares a single items from ngonPairs (i.e. arrays), and we can then use SequenceEqual described above to compare each of those arrays to our known array.




回答2:


List contains an array object, but you are trying to search for another newly created object. Both array objects are different, so it always return false. If your intention is to compare the values of the array, you can use EqualityComparer to check.

Write a comparer to compare two arrays. Following code snippet is the example and it will just compare int array of size two.

class ArrayComparer : EqualityComparer<int[]>
    {
        public override bool Equals(int[] x, int[] y)
        {

            if (x[0] == y[0] && x[1] == y[1])
                return true;
            else
                return false;
        }

        public override int GetHashCode(int[] obj)
        {
            throw new NotImplementedException();
        }
    }

Then use this EqualityComparer instance in the Contains function to compare the array values;

bool flag = ngonPairs.Contains(new int[2] { 0, 1 }, new ArrayComparer());


来源:https://stackoverflow.com/questions/44789252/checking-for-an-array-in-a-list-with-listint-containsnew-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!