📜  C#中的Stack.Contains()方法

📅  最后修改于: 2021-05-29 16:20:28             🧑  作者: Mango

此方法(位于System.Collections命名空间下)用于检查存在的指定元素是否为Stack。在内部,此方法通过调用Object.Equals方法检查是否相等。另外,它执行线性搜索,因此,此方法是O(n)运算,其中n是Count。

句法:

public virtual bool Contains (object obj);

在这里, obj是要在堆栈中定位的对象。该值可以为null

返回值:如果在堆栈中找到obj ,则返回true ,否则返回false

下面的程序说明了上面讨论的方法的使用:

范例1:

// C# code to illustrate the
// Stack.Contains() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements into the Stack
        myStack.Push("Geeks");
        myStack.Push("Geeks Classes");
        myStack.Push("Noida");
        myStack.Push("Data Structures");
        myStack.Push("GeeksforGeeks");
  
        // Checking whether the element is
        // present in the Stack or not
        // The function returns True if the
        // element is present in the Stack, 
        // else returns False
        Console.WriteLine(myStack.Contains("GeeksforGeeks"));
    }
}
输出:
True

范例2:

// C# code to illustrate the
// Stack.Contains() Method
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Stack
        Stack myStack = new Stack();
  
        // Inserting the elements 
        // into the Stack
        myStack.Push(5);
        myStack.Push(10);
        myStack.Push(15);
        myStack.Push(20);
        myStack.Push(25);
  
        // Checking whether the element is
        // present in the Stack or not
        // The function returns True if the
        // element is present in the Stack, else
        // returns False
        Console.WriteLine(myStack.Contains(7));
    }
}
输出:
False

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.contains?view=netframework-4.7.2