Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
queue
contains
communitycreator

How to check if an item is present in the queue

Surabhi Sharma

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.

Syntax

public bool Contains (T item);
  • It takes an object of the T type as input to search in the queue and returns a Boolean result.

  • It uses EqualityComparer<T>.Default for Tthe type of value in the queue to determine quality.

  • 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.

Example

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"));        
    }
}

RELATED TAGS

c#
queue
contains
communitycreator
RELATED COURSES

View all Courses

Keep Exploring