我创建了一个程序,其中有一个int数组队列:
Queue< int[] > Test = new Queue< int[] >();
给定一个数组,我想检查该数组是否在队列内。
我当前使用的名称空间是:System,System.Collections和System.Collections.Generic。
我尝试过这样的事情:
Queue<int[]> Test = new Queue<int[]>();
Test.Enqueue(new int[] { 20, 20 });
Console.WriteLine( Test.Contains(new int[] { 20, 20 }) ); // Is the array {20,20} inside the queue?
在这段代码中,在我看来控制台将输出“ true”,因为我将数组{20,20}添加到了队列中,现在我正在使用Contains方法进行检查。
但是,当我运行代码时,控制台输出为false。
我有两个问题:为什么会这样?我该如何解决呢?
由于数组是引用类型,因此比较将基于引用。即使内容相同,您的数组也会有不同的引用,这就是为什么您会得到false的原因。
要解决此问题,您可以实现自定义比较器,也可以使用LINQ
例如方法
bool arrayExists = Test.Any(x => x.SequenceEqual(new[] { 20, 20 }));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句