如何确定数组是否在堆栈中?

时间:2017-11-02 16:30:03

标签: c# arrays stack contains any

所以我试图确定堆栈中是否有相同值的数组。

Stack<string> stackOfStrings = new Stack<string>();
stackOfStrings.Push("dog");
stackOfStrings.Push("cat");
Debug.WriteLine("stackOfString contains cat: " + 
    stackOfStrings.Contains("cat"));
Debug.WriteLine("stackOfString contains dog: " + 
    stackOfStrings.Contains("dog"));

Stack<int[]> stackOfIntArrays = new Stack<int[]>();
stackOfIntArrays.Push(new int[]{0,1});
stackOfIntArrays.Push(new int[]{1,1});
int[] array01 = new int[]{0,1};
int[] anotherArray01 = new int[]{0,1};
int[] array11 = new int[] { 1, 1 };

Debug.WriteLine("SequenceEqual can compare arrays of identical value: " + array01.SequenceEqual(anotherArray01));
Debug.WriteLine("SequenceEqual can be used to compare the top value of a stack: " + stackOfIntArrays.Peek().SequenceEqual(array11));
//I want the line below to evaluate to true 
Debug.WriteLine("Contains can be used to determine if an array of values is within the stack: " + stackOfIntArrays.Contains(array01));

以下是代码的输出:

stackOfString contains cat: True
stackOfString contains dog: True
SequenceEqual can compare arrays of identical value: True
SequenceEqual can be used to compare the top value of a stack: True
Contains can be used to determine if an array of values is within the stack: False

我对这方面的研究已经发现很多结果,看看数组是在另一个数组中还是另一个数组的子集,这就是我学习SequenceEqual的方法。看到它似乎只能检查堆栈中的最高值,它不足以满足我的需求。

我考虑过的替代解决方案是将堆栈重新堆叠到新堆栈并检查每个阵列的移动情况。但是,考虑到包含可以在整个堆栈中查找string类型的值,我得出的结论是int []类型的值应该是可能的。如果没有,我们将不胜感激为您提供最佳解决方案的指导。

1 个答案:

答案 0 :(得分:0)

使用LINQ的Any而不是Contains来检查除相等之外的条件:

Debug.WriteLine(
    "Enumerable.Any can be used to determine if an array of values is within the stack: {0}"
,   stackOfIntArrays.Any(a => array01. SequenceEqual(a))
);

这相当于任意条件的“包含if ...”实现。