Queue.Contains() method with example in C#

C# Queue.Contains() technique: Here, we will find out about the Contains() strategy for Queue class in C#.

C# Queue.Contains() technique

Queue.Contains() technique is utilized to check whether a given article/component exists in a Queue or not, it returns genuine if object/component exists in the line else it returns bogus.

Syntax:

    bool Queue.Contains(Object);

Parameters: Object – object/component to be checked.

Return value: bool – it restores a Boolean value, genuine – if an object exists in the Queue, bogus – if the object doesn’t exist in the Queue.

Example:

    declare and initialize a Queue:
    Queue que = new Queue();   

    insertting elements:
    que.Enqueue(100);
    que.Enqueue(200);
    que.Enqueue(300);
    que.Enqueue(400);
    que.Enqueue(500);
    
    checking elements:
    que.Contains(100);
    que.Contains(500);
    que.Contains(600);

    Output:
    true
    true
    false

C# example to check whether an article/component exists in the Queue or not utilizing Queue.Contains() technique

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print queue elements
        static void printQueue(Queue q)
        {
            foreach (Object obj in q)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //declare and initialize a Queue
            Queue que = new Queue();

            //insertting elements
            que.Enqueue(100);
            que.Enqueue(200);
            que.Enqueue(300);
            que.Enqueue(400);
            que.Enqueue(500);

            //printing Queue elements
            Console.WriteLine("Queue elements...");
            printQueue(que);

            //checking elements
            if (que.Contains(100) == true)
                Console.WriteLine("100 exists in the Queue...");
            else
                Console.WriteLine("100 does not exist in the Queue...");

            if (que.Contains(200) == true)
                Console.WriteLine("200 exists in the Queue...");
            else
                Console.WriteLine("200 does not exist in the Queue...");

            if (que.Contains(600) == true)
                Console.WriteLine("600 exists in the Queue...");
            else
                Console.WriteLine("600 does not exist in the Queue...");

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Queue elements...
100 200 300 400 500
100 exists in the Queue...
200 exists in the Queue...
600 does not exist in the Queue...

Leave a Comment

error: Alert: Content is protected!!