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

📅  最后修改于: 2021-05-29 21:18:07             🧑  作者: Mango

此方法用于检查元素是否在队列中。此方法执行线性搜索,因此,此方法是O(n)运算,其中n是Count。而且此方法位于System.Collections命名空间下。

句法:

public virtual bool Contains(object obj);

在这里, obj是要在队列中定位的对象。该值可以为空。

返回值:如果该元素存在于队列中,则该函数返回True;如果该元素不存在于Queue中,则该函数返回False

下面给出了一些示例,以更好地理解实现:

范例1:

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


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


输出:
False

范例2:

C#

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

参考:

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