List<int[]>的Contains方法不生效,如何检测数组是否存在于列表中?
问题原因
数组是引用类型,List<T>.Contains()默认采用引用相等性判断——只有当两个数组是同一个对象实例时,才会返回true。你代码里的testing是新创建的数组实例,和列表中存储的{7,8}数组是不同的对象,所以Contains()返回false,控制台输出Failure。
几种简单的解决方法
方法1:使用Any() + SequenceEqual()
这是最直接的临时解决方案,通过逐元素比较数组内容来判断是否存在匹配项:
static void Main(string[] args) { List<int[]> listInt = new List<int[]>(); // ... 省略添加数组的代码 int[] testing = new int[] { 7, 8 }; if (listInt.Any(arr => arr.SequenceEqual(testing))) { Console.WriteLine("Success"); } else { Console.WriteLine("Failure"); } }
SequenceEqual()会严格比较两个数组的元素顺序和值,完全一致才返回true;Any()只要找到一个匹配的数组就立即返回true,无需遍历整个列表。
方法2:自定义相等比较器
如果需要多次进行这类数组包含检查,建议自定义一个相等比较器,复用性更强:
首先定义比较器类:
public class IntArrayEqualityComparer : IEqualityComparer<int[]> { public bool Equals(int[] x, int[] y) { if (x == null || y == null) return x == y; // 处理null的情况 return x.SequenceEqual(y); } public int GetHashCode(int[] obj) { if (obj == null) return 0; int hash = 17; foreach (int num in obj) { hash = hash * 31 + num.GetHashCode(); } return hash; } }
然后在Contains()中传入这个比较器:
if (listInt.Contains(testing, new IntArrayEqualityComparer())) { Console.WriteLine("Success"); } else { Console.WriteLine("Failure"); }
方法3:改用值类型集合(适用于固定长度的数组)
如果你的数组长度固定(比如示例中的2个元素),可以用C#的元组(值类型)替代数组,这样Contains()会直接比较值而非引用:
static void Main(string[] args) { List<(int, int)> listInt = new List<(int, int)>(); listInt.Add((1, 2)); listInt.Add((3, 4)); listInt.Add((5, 6)); listInt.Add((7, 8)); // ... 省略其他元素 var testing = (7, 8); if (listInt.Contains(testing)) { Console.WriteLine("Success"); } else { Console.WriteLine("Failure"); } }
内容的提问来源于stack exchange,提问作者Sean
相关产品推荐
相关产品推荐

