Home » C#.Net

Queue.Contains() method with example in C#

C# Queue.Contains() method: Here, we are going to learn about the Contains() method of Queue class in C#.
Submitted by IncludeHelp, on March 30, 2019

C# Queue.Contains() method

Queue.Contains() method is used to check whether a given object/element exists in a Queue or not, it returns true if object/element exists in the queue else it returns false.

Syntax:

    bool Queue.Contains(Object);

Parameters: Object – object/element to be checked.

Return value: bool – it returns a Boolean value, true – if object exists in the Queue, false – if object does not exists 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 object/element exists in the Queue or not using Queue.Contains() method

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

Reference: Queue.Contains(Object) Method



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.