Phương thức Queue.Peek () trong C # được sử dụng để trả về đối tượng ở đầu Hàng đợi mà không xóa nó.
Cú pháp
Cú pháp như sau -
public virtual object Peek ();
Ví dụ
Bây giờ chúng ta hãy xem một ví dụ -
using System;
using System.Collections;
public class Demo {
public static void Main() {
Queue queue = new Queue();
queue.Enqueue("AB");
queue.Enqueue("BC");
queue.Enqueue("CD");
queue.Enqueue("DE");
queue.Enqueue("EF");
queue.Enqueue("FG");
queue.Enqueue("GH");
queue.Enqueue("HI");
Console.WriteLine("Queue...");
IEnumerator demoEnum = queue.GetEnumerator();
while (demoEnum.MoveNext()) {
Console.WriteLine(demoEnum.Current);
}
Console.WriteLine("Queue element at the beginning = "+queue.Peek());
Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized);
Queue queue2 = Queue.Synchronized(queue);
Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized);
}
} Đầu ra
Điều này sẽ tạo ra kết quả sau -
Queue... AB BC CD DE EF FG GH HI Queue element at the beginning = AB Is Queue synchronized? = False Is Queue synchronized now? = True
Ví dụ
Bây giờ chúng ta hãy xem một ví dụ khác -
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("Queue element at the beginning = "+queue.Peek());
Console.WriteLine("Does the queue has element Jack? = "+queue.Contains("Jack"));
queue.Clear();
Console.Write("Count of elements (updated) = ");
Console.WriteLine(queue.Count);
}
} Đầu ra
Điều này sẽ tạo ra kết quả sau -
Count of elements = 8 Queue element at the beginning = Gary Does the queue has element Jack? = True Count of elements (updated) = 0