Queue.Contains() Method in C#


The Queue.Contains() method in C# is used to determine whether an element is in the Queue.

Syntax

The syntax is as follows -

public virtual bool Contains (object ob);

Above, the parameter ob is the Object to locate in the Queue.

Example

Let us now see an example -

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Does the queue has element Jack? = "+queue.Contains("Jack"));
      queue.Clear();
      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

Output

This will produce the following output -

Count of elements = 8
Does the queue has element Jack? = True
Count of elements (updated) = 0

Example

Let us now see another example -

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);
      Console.WriteLine("Does the queue has element 500? = "+queue.Contains(500));
      queue.Clear();
      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

Output

This will produce the following output -

Count of elements = 3
Does the queue has element 500? = False
Count of elements (updated) = 0
raja
Published on 03-Dec-2019 13:17:35
Advertisements