Queue<T>クラス

Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);

foreach (int value in queue)
{
    Console.Write(value);
} // 123

Console.Write(queue.Dequeue()); // 1
Console.Write(queue.Dequeue()); // 2
Console.Write(queue.Dequeue()); // 3
Console.Write(queue.Dequeue()); // InvalidOperationException: Queue が空です。

実装しているインターフェイス

[SerializableAttribute]
[ComVisibleAttribute(false)]
public class Queue<T> :
    IEnumerable<T>,
    IEnumerable,
    ICollection,
    IReadOnlyCollection<T>
構文 - Queue(T) クラス (System.Collections.Generic) | MSDN

コンストラクタ

コンストラクタ  
Queue<T>()  
Queue<T>(IEnumerable<T>)  
Queue<T>(Int32)  

Queue<T>(IEnumerable<T>)

public Queue(
    IEnumerable<T> collection
)
Queue(T) コンストラクター (IEnumerable(T)) (System.Collections.Generic) | MSDN

Queue<T>(Int32)

public Queue(
    int capacity
)
Queue(T) コンストラクター (Int32) (System.Collections.Generic) | MSDN

コレクションのサイズを見積もれるならばそれを指定することで、要素を追加したときのサイズ変更の処理を削減できます。

このコンストラクタの計算量は、capacityをnとしてO(n)です。

プロパティ

プロパティ 内容
int Count 要素の数

メソッド

戻り値の型 メソッド 機能
void Enqueue(T) 末尾に要素を、追加する
T Dequeue() 先頭にある要素を、削除して返す
T Peek() 先頭にある要素を、削除せず返す
void TrimExcess() 実際の要素数が現在の容量の90%未満ならば、容量をその数に設定できる
T[] ToArray() 要素を新しい配列にコピーできる
bool Contains(T) 要素がコレクション内に存在するか確認できる
   
メソッド - Queue<T> クラス (System.Collections.Generic) | Microsoft Learn

返す要素が存在しないときにDequeue()やPeek()を呼び出すと、InvalidOperationException例外が発生します。よって要素の存在が明らかではないならば、事前にCountで要素数を確認すべきです。

if (0 < queue.Count)
{
    Console.Write(queue.Dequeue());
}

Enqueue(T)

public void Enqueue (T item);
Queue<T>.Enqueue(T) Method (System.Collections.Generic) | Microsoft Learn

計算量は、内部容量よりCountが小さければO(1)ですが、新しい要素のために再割り当てが必要ならば、nをCountとしてO(n)となります。Remarks - Queue<T>.Enqueue(T) Method (System.Collections.Generic) | Microsoft Learn

複数の要素の追加

Enqueue(T)では1つずつしか要素を追加できないため、複数の要素を追加するにはくり返しこのメソッドを呼ぶ必要があります。そのときコレクションがListならば、ForEach()により簡潔に記述できます。

List<int> list = new List<int>(new int[] { 1, 2, 3 });
Queue<int> queue1 = new Queue<int>();

list.ForEach(v => queue1.Enqueue(v)); // すべての要素でEnqueue()を呼ぶ
list.ForEach(queue1.Enqueue);         // 引数を省略しても同じ

同様のことはArray.ForEach()でも可能です。

int[] array = new int[] { 4, 5, 6 };

Array.ForEach(array, queue1.Enqueue);

またはオブジェクトの生成時に追加するならば、Queue<T>のコンストラクタがIEnumerable<T>も引数に取ることを利用し、次のようにも記述できます。

List<int> list = new List<int>(new int[] { 1, 2, 3 });
Queue<int> queue2 = new Queue<int>(list);
collections - How to Enqueue a list of items in C#? - Stack Overflow

ToArray()

public T[] ToArray ();
Queue<T>.ToArray メソッド (System.Collections.Generic) | Microsoft Learn

内部ではArray.Copy()で、新しい配列に要素をコピーしているだけです。ToArray - queue.cs

計算量はCountをnとして、O(n)です。Remarks - Queue<T>.ToArray Method (System.Collections.Generic) | Microsoft Learn

Contains(T)

public bool Contains (T item);
Queue<T>.Contains(T) メソッド (System.Collections.Generic) | Microsoft Learn

線形検索で実行されるため、計算量はCountをnとしてO(n)です。

Microsoft Learnから検索