搜索
您的当前位置:首页c#集合之二队列

c#集合之二队列

来源:乌哈旅游

在之前,知道队列,但是不知道队列在c#中是一个集合类

Queue :队列,表示对象的先进先出集合。Enqueue方法入队列,Dequeue方法出队列。

刚刚看了看Msdn,并练习了一下关于Queue的相关代码:
 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Text;
 4
 5 using  System.Collections;
 6
 7 namespace  Practice
 8 {
 9      public   class  Cs_Queue
10      {
11          private  Queue myQueue  =   null ;
12
13          public  Cs_Queue()
14          {
15              // Queue默认大小为8个
16             myQueue  =   new  Queue();
17             // 使用Enqueue对队列进行初始化,注意队列中的先进先出规则
18             myQueue.Enqueue( " a " );
19             myQueue.Enqueue( " b " );
20             myQueue.Enqueue( " c " );
21             myQueue.Enqueue( 2 );
22              // 将队列的容量设置为元素的实际数量
23             myQueue.TrimToSize();
24         }

25
26          public  Cs_Queue(ICollection collecrions)
27          {
28              // 根据外来的集合类型来进行初始化队列
29             myQueue  =   new  Queue(collecrions);
30         }

31
32          // 打印队列中的元素
33          public   void  PrintQuene()
34          {
35              // 打印队列中的元素
36             Console.WriteLine( " Queue has elements: " );
37              foreach  ( object  obj  in  myQueue)
38              {
39                 Console.WriteLine( " {0}, " , obj.ToString());
40             }

41
42              // 当队列中出现了出队事件时,打印出队的元素和出对前的队首元素以及出对后的队首元素
43              // myQueue.Peek()获取队列中处于队首的元素
44              // myQueue.Dequeue()获取队列中出队列的元素
45             Console.WriteLine( " the element on the first of the Queue before the Queue Dequeue: " );
46             Console.WriteLine( " {0} " ,myQueue.Peek().ToString());
47             Console.WriteLine( " the element out of the Queue: " );
48             Console.WriteLine( " {0} " ,myQueue.Dequeue().ToString());
49             Console.WriteLine( " the element on the first of the Qune after the Queue DeQueue: " );
50             Console.WriteLine( " {0} " , myQueue.Peek().ToString());
51             Console.ReadLine();
52         }

53
54     }

55 }

初始化队列时的代码:

1         private   void  TestQueue()
2          {
3             Cs_Queue myCs1  =   new  Cs_Queue();
4             ICollection collection  =   new   object []  { " a " , " b " , " c " , 1 } ;
5             Cs_Queue myCs2  =   new  Cs_Queue(collection);
6             myCs1.PrintQuene();
7             myCs2.PrintQuene();
8         }

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Top