The Queue<T>
generic class in the System.Collections.Generic
namespace provides the Contains()
method, which can be used to check if an item exists in the queue. This method returns true
if the element is present in the queue, and returns false
otherwise.
public bool Contains (T item);
It takes an object of the T
type as input to search in the queue
It uses EqualityComparer<T>.Default
for
The time complexity of this method is O(n), where n is the count of elements as it performs a linear search in the array.
In the below example, we create a queue of strings and add the names of the first six calendar months to it. We then print all the elements of the queue.
We check the presence of April
with the Contains()
method, which returns true
, as it is present in the queue.
After that, we check the presence of December
with the Contains()
method. This returns false
, as the queue does not contain December
.
using System;using System.Collections.Generic;class QueueContains{static void Main(){Queue<string> months = new Queue<string>();months.Enqueue("January");months.Enqueue("February");months.Enqueue("March");months.Enqueue("April");months.Enqueue("May");months.Enqueue("June");Console.WriteLine("Queue Items : {0}", string.Join(",", months.ToArray()));Console.WriteLine("Does Queue Contains 'April'? : {0}",months.Contains("April"));Console.WriteLine("Does Queue Contains 'December' ?: {0}",months.Contains("December"));}}