使用"List< int []>.Contains(new int [] {..}))"检查列表中的数组,总是返回false [英] Checking for an array in a list, with "List<int[]>.Contains(new int[] { .. })", always returns false

查看:53
本文介绍了使用"List< int []>.Contains(new int [] {..}))"检查列表中的数组,总是返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查由int [2]数组组成的列表是否包含某些元素.

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

标记始终为假.

推荐答案

这是因为

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

它们是不同的数组,对一个数组的更改不会反映在另一个数组中.

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

但是,使用LINQ的 SequenceEqual ,您可以比较两个序列的 内容 :

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

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

现在,使用LINQ的 Any ,您可以:

Now, using LINQ's Any you could:

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

.任何在一个序列上进行操作,如果序列中的任何一项满足谓词,则返回 true .

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

在这种情况下,谓词比较来自 ngonPairs 的单个项(即数组),然后我们可以使用上述的 SequenceEqual 将每个数组与我们的数组进行比较已知数组.

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.

这篇关于使用"List&lt; int []>.Contains(new int [] {..}))"检查列表中的数组,总是返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆