当前位置: 首页>>代码示例>>C#>>正文


C# Queue类代码示例

本文整理汇总了C#中Queue的典型用法代码示例。如果您正苦于以下问题:C# Queue类的具体用法?C# Queue怎么用?C# Queue使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


Queue类属于命名空间,在下文中一共展示了Queue类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        static void Main(string[] args)
        {
            const int NumberOfAnimals = 10;
            Stack<Animal> animalStack = new Stack<Animal>();
            Queue<Animal> animalQueue = new Queue<Animal>();

            Console.WriteLine("/// ORDER OF ENTRY...");
            Random r = new Random();
            for (int index = 0; index < NumberOfAnimals; index++)
            {
                var animalShouldBeCat = (r.Next(2) == 0);
                uint nextWeight = (uint)r.Next(10, 40);
                Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
                animalStack.Push(nextAnimal);
                animalQueue.Enqueue(nextAnimal);
                Console.WriteLine(nextAnimal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM STACK...");
            foreach (Animal animal in animalStack)
            {
                Console.WriteLine(animal);
            }

            Console.WriteLine();
            Console.WriteLine("/// OUTPUT FROM QUEUE...");
            foreach (Animal animal in animalQueue)
            {
                Console.WriteLine(animal);
            }
        }
开发者ID:JackMorris,项目名称:LCS3,代码行数:32,代码来源:Program.cs

示例2: CollectEntities

        private void CollectEntities(int addr, Dictionary<int, Entity> list)
        {
            int num = addr;
            addr = M.ReadInt(addr + 4);
            var hashSet = new HashSet<int>();
            var queue = new Queue<int>();
            queue.Enqueue(addr);
            while (queue.Count > 0)
            {
                int nextAddr = queue.Dequeue();
                if (hashSet.Contains(nextAddr))
                    continue;

                hashSet.Add(nextAddr);
                if (M.ReadByte(nextAddr + 21) == 0 && nextAddr != num && nextAddr != 0)
                {
                    int key = M.ReadInt(nextAddr + 12);
                    if (!list.ContainsKey(key))
                    {
                        int address = M.ReadInt(nextAddr + 16);
                        var entity = base.GetObject<Entity>(address);
                        list.Add(key, entity);
                    }
                    queue.Enqueue(M.ReadInt(nextAddr));
                    queue.Enqueue(M.ReadInt(nextAddr + 8));
                }
            }
        }
开发者ID:hunkiller,项目名称:PoeHud,代码行数:28,代码来源:EntityList.cs

示例3: BFS

    private int BFS(int startEdge, int endEdge)
    {
        bool[] used = new bool[MaxNumber + 1];
        int level = 0;
        Queue<int> nodesQueue = new Queue<int>();
        nodesQueue.Enqueue(startEdge);
        while (nodesQueue.Count > 0)
        {
            Queue<int> nextLevelNodes = new Queue<int>();
            level++;
            while (nodesQueue.Count > 0)
            {
                int node = nodesQueue.Dequeue();
                if (node == endEdge)
                {
                    return level - 1;
                }

                // Pressing the left button
                for (int i = 0; i < WheelsCount; i++)
                {
                    int newNode = node;
                    int digit = (node / powerOf10[i]) % 10;
                    if (digit == 9)
                    {
                        newNode -= 9 * powerOf10[i];
                    }
                    else
                    {
                        newNode += powerOf10[i];
                    }
                    if (used[newNode]) continue;
                    if (isForbiddenEdge[newNode]) continue;
                    used[newNode] = true;
                    nextLevelNodes.Enqueue(newNode);
                }

                // Pressing the right button
                for (int i = 0; i < WheelsCount; i++)
                {
                    int newNode = node;
                    int digit = (node / powerOf10[i]) % 10;
                    if (digit == 0)
                    {
                        newNode += 9 * powerOf10[i];
                    }
                    else
                    {
                        newNode -= powerOf10[i];
                    }
                    if (used[newNode]) continue;
                    if (isForbiddenEdge[newNode]) continue;
                    used[newNode] = true;
                    nextLevelNodes.Enqueue(newNode);
                }
            }
            nodesQueue = nextLevelNodes;
        }
        return -1;
    }
开发者ID:staafl,项目名称:ta-hw-dsa,代码行数:60,代码来源:program.cs

示例4: PlayMessage

 public void PlayMessage(Queue<string> messages)
 {
     dialogue.gameObject.SetActive(true);
     player.state = Player.State.Interacting;
     msgQueue = messages;
     PlayNextMessage();
 }
开发者ID:FredrikLH,项目名称:Hex666,代码行数:7,代码来源:GameManager.cs

示例5: DashboardView

        public DashboardView()
        {
            InitializeComponent();

            AndonManager = new AndonManager(StationList, null, Andonmanager.AndonManager.MODE.MASTER);

            AndonManager.start();
            StationList = new Queue<int>();

            Plans = new Plans();
            PlanGrid.DataContext = Plans;

            Actuals = new Models.Actuals();
            ActualGrid.DataContext = Actuals;

            AppTimer = new Timer(1000);
            AppTimer.AutoReset = false;
            AppTimer.Elapsed += AppTimer_Elapsed;

            EfficiencyWatch = new Stopwatch();

            using (PSBContext DBContext = new PSBContext())
            {

                Shifts = DBContext.Shifts.ToList();

                foreach (Shift s in Shifts)
                {
                    s.Update();
                }

            }

            AppTimer.Start();
        }
开发者ID:JugaadSolutions,项目名称:ProductionScoreBoard,代码行数:35,代码来源:DashboardView.xaml.cs

示例6: TraverseWithBFS

 private static void TraverseWithBFS(string[,] matrix, Cell startCell)
 {
     Queue<Cell> visitedCells = new Queue<Cell>();
     visitedCells.Enqueue(startCell);
     while (visitedCells.Count > 0)
     {
         Cell cell = visitedCells.Dequeue();
         int row = cell.Row;
         int col = cell.Col;
         int dist = cell.Distance;
         matrix[row, col] = dist.ToString();
         if (IsInMatrix(matrix, row + 1, col) && matrix[row + 1, col] == "0")
         {
             visitedCells.Enqueue(new Cell(row + 1, col, dist + 1));
         }
         if (IsInMatrix(matrix, row, col + 1) && matrix[row, col + 1] == "0")
         {
             visitedCells.Enqueue(new Cell(row, col + 1, dist + 1));
         }
         if (IsInMatrix(matrix, row - 1, col) && matrix[row - 1, col] == "0")
         {
             visitedCells.Enqueue(new Cell(row - 1, col, dist + 1));
         }
         if (IsInMatrix(matrix, row, col - 1) && matrix[row, col - 1] == "0")
         {
             visitedCells.Enqueue(new Cell(row, col - 1, dist + 1));
         }
     }
 }
开发者ID:dchakov,项目名称:Data-Structures-and-Algorithms_HW,代码行数:29,代码来源:StartUp.cs

示例7: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("PosTest1: Test whether Peek() is successful when the queue is not empty.");

        try
        {
            Queue<string> TestQueue = new Queue<string>();
            TestQueue.Enqueue("one");
            TestQueue.Enqueue("two");
            TestQueue.Enqueue("three");
            string PeekResult = TestQueue.Peek();
            if (PeekResult != "one")
            {
                TestLibrary.TestFramework.LogError("P01.1", "Peek() failed! Expected value is "+"\"one\". But actual value is \""+PeekResult+"\".");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogVerbose(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:27,代码来源:queuepeek.cs

示例8: BreadthFirstSearch

 public BreadthFirstSearch(Graph graph)
 {
     this.graph = graph;
     traversedVertex = new bool[graph.Vertices.Count()];
     queueVertices = new Queue<int>();
     distance = new int[graph.Vertices.Count()];
 }
开发者ID:Miltt,项目名称:Console,代码行数:7,代码来源:Program.cs

示例9: Main

    static void Main()
    {
        //S1 = N;
        //S2 = S1 + 1;
        //S3 = 2 * S1 + 1;
        //S4 = S1 + 2;
        //S5 = S2 + 1;
        //S6 = 2 * S2 + 1;
        //S7 = S2 + 2;
        //Using the Queue<T> class write a program to print its first 50 members for given N.
        //Example: N=2 -> 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...

        Queue<int> queue = new Queue<int>();
        queue.Enqueue(2);
        for (int i = 1; i <= 50; i++)
        {
            int s = queue.Dequeue();

            queue.Enqueue(s + 1);
            queue.Enqueue(2 * s + 1);
            queue.Enqueue(s + 2);

            Console.WriteLine("{0}. {1}", i, s);
        }
    }
开发者ID:bahtev,项目名称:TelerikAcademy,代码行数:25,代码来源:SequenceMembers.cs

示例10: MatchFormat

        public static List<Tuple<String, String>> MatchFormat(String Format, String Line)
        {
            var Matches = new List<Tuple<String, String>>();

            var FormatChunks = new Queue<String>(Tokenize(Format));
            var LineChunks = new Queue<String>(Tokenize(Line));

            while (FormatChunks.Count > 0)
            {
                var CurrentFormat = FormatChunks.Dequeue();
                var CurrentLine = LineChunks.Dequeue();

                switch (CurrentFormat)
                {
                    default:
                        if (CurrentFormat[0] == '%')
                        {
                            Matches.Add(new Tuple<String, String>(CurrentFormat, CurrentLine));
                        }
                        else
                        {
                            if (CurrentLine != CurrentFormat) throw (new InvalidDataException());
                        }
                        break;
                }
            }

            if (LineChunks.Count > 0)
            {
                throw (new InvalidDataException("Unexpected token '" + LineChunks.Dequeue() + "' on '" + Line + "' for format '" + Format + "'"));
            }

            return Matches;
        }
开发者ID:mrcmunir,项目名称:cspspemu,代码行数:34,代码来源:MipsAssembler.cs

示例11: RetriesWhenResendRequested

            public async Task RetriesWhenResendRequested()
            {
                var firstResponse = new TwoFactorRequiredException(TwoFactorType.AuthenticatorApp);
                var challengeResults = new Queue<TwoFactorChallengeResult>(new[]
                {
                    TwoFactorChallengeResult.RequestResendCode,
                    new TwoFactorChallengeResult("two-factor-code")
                });
                var secondResponse = new Authorization { Token = "OAUTHSECRET" };

                var client = Substitute.For<IObservableAuthorizationsClient>();
                client.GetOrCreateApplicationAuthentication(Args.String, Args.String, Args.NewAuthorization)
                    .Returns(Observable.Throw<Authorization>(firstResponse));
                client.GetOrCreateApplicationAuthentication(
                    Args.String,
                    Args.String,
                    Args.NewAuthorization,
                    "two-factor-code")
                    .Returns(Observable.Return(secondResponse));

                var result = await client.GetOrCreateApplicationAuthentication(
                    "clientId",
                    "secret",
                    new NewAuthorization { Note = "Was it this one?" },
                    _ => Observable.Return(challengeResults.Dequeue()));

                client.Received(2).GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>());
                client.Received().GetOrCreateApplicationAuthentication("clientId",
                    "secret",
                    Arg.Any<NewAuthorization>(), "two-factor-code");
                Assert.Equal("OAUTHSECRET", result.Token);
            }
开发者ID:KimCM,项目名称:octokit.net,代码行数:34,代码来源:AuthorizationExtensionsTests.cs

示例12: EnqueueRecursive

		public static void EnqueueRecursive(AbstractProjectBrowserTreeNode node)
		{
			lock (queue) {
				if (inQueue.Add(node))
					queue.Enqueue(node);
				// use breadth-first search
				Queue<AbstractProjectBrowserTreeNode> q = new Queue<AbstractProjectBrowserTreeNode>();
				q.Enqueue(node);
				while (q.Count > 0) {
					node = q.Dequeue();
					foreach (TreeNode n in node.Nodes) {
						node = n as AbstractProjectBrowserTreeNode;
						if (node != null) {
							q.Enqueue(node);
							if (inQueue.Add(node))
								queue.Enqueue(node);
						}
					}
				}
				
				if (!threadRunning) {
					threadRunning = true;
					ThreadPool.QueueUserWorkItem(Run);
				}
			}
		}
开发者ID:Paccc,项目名称:SharpDevelop,代码行数:26,代码来源:OverlayIconManager.cs

示例13: Execute

        public bool Execute(params object[] stuff)
        {
            if (Room == null) return false;
            Queue<RoomItem> toRemove = new Queue<RoomItem>();

            if (Items.Any())
            {
                foreach (RoomItem item in Items)
                {
                    if (item == null || Room.GetRoomItemHandler().GetItem(item.Id) == null)
                    {
                        toRemove.Enqueue(item);
                        continue;
                    }

                    HandleMovement(item);
                }
            }


            while (toRemove.Count > 0)
            {
                RoomItem itemToRemove = toRemove.Dequeue();

                if (Items.Contains(itemToRemove))
                    Items.Remove(itemToRemove);
            }

            return true;
        }
开发者ID:weslley17w,项目名称:Yupi,代码行数:30,代码来源:Chase.cs

示例14: MapItem

        protected MapItem(IntVector2 hexQuoords, World world)
        {
            HexQuoordinates = hexQuoords;
            World = world;

            Tasks = new Queue<Task>();
        }
开发者ID:poohshoes,项目名称:HexGame,代码行数:7,代码来源:MapItem.cs

示例15: Eywi

        public Eywi(string fileName)
        {
            IEnumerator<string> iter = File.ReadLines(fileName).GetEnumerator();
            if (iter.MoveNext())
            {
                string firstLine = iter.Current;
                string[] firsts = firstLine.Split(' ');
                if (firsts[0].StartsWith("VERSION="))
                    Version = int.Parse(firsts[0].Substring("VERSION=".Length));
                if (firsts[1].StartsWith("UID="))
                    Uid = ushort.Parse(firsts[1].Substring("UID=".Length));
                if (firsts.Length > 2 && firsts[2].StartsWith("ENCRY=0"))
                    Encryed = false;
                else
                    Encryed = true;
            }
            magnification = new float[] { 0.25f, 0.5f, 1, 2, 4, 8 };
            magnificationFlat = new float[] { 0.75f, 0.9f, 1, 1.25f, 1.75f, 2.5f };
            magnificationstr = new string[] { "0.25", "0.5", "1", "2", "4", "8" };
            mMagIndex = 2;
            mInProcess = true;
            yMessage = new Queue<string>();

            dixits = new List<string>();
            while (iter.MoveNext())
                dixits.Add(iter.Current);
            dixitCursor = 0;
        }
开发者ID:palome06,项目名称:psd48,代码行数:28,代码来源:Eywi.cs


注:本文中的Queue类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。