• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Queue类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Search

        static IEnumerable<string> Search(string root, string searchPattern)
        {
            // taken from: http://stackoverflow.com/a/438316/105999
            Queue<string> dirs = new Queue<string>();
            dirs.Enqueue(root);
            while (dirs.Count > 0) {
                string dir = dirs.Dequeue();

                // files
                string[] paths = null;
                try {
                    paths = Directory.GetFiles(dir, searchPattern);
                }
                catch(Exception ex) { } // swallow

                if (paths != null && paths.Length > 0) {
                    foreach (string file in paths) {
                        yield return file;
                    }
                }

                // sub-directories
                paths = null;
                try {
                    paths = Directory.GetDirectories(dir);
                }
                catch(Exception ex) { } // swallow

                if (paths != null && paths.Length > 0) {
                    foreach (string subDir in paths) {
                        dirs.Enqueue(subDir);
                    }
                }
            }
        }
开发者ID:NileshMoradiya,项目名称:template-builder,代码行数:35,代码来源:RobustReplacer.cs


示例17: GenerateTileMap

	public void GenerateTileMap()
	{
		allTileCoords = new List<Coord> ();

		for (int x = 0; x < mapSize.x; x ++) {

			for (int y = 0; y < mapSize.y; y ++) {

				allTileCoords.Add(new Coord(x,y));

			}

		}

		shuffledTileCoords = new Queue<Coord> (Utility.ShuffleArray (allTileCoords.ToArray (), seed));

		string holderName = "Generated Map";

		if (transform.FindChild (holderName)) {

			DestroyImmediate (transform.FindChild (holderName).gameObject);
		}

		Transform mapHolder = new GameObject (holderName).transform;
		mapHolder.parent = transform;

		for (int x = 0; x < mapSize.x; x ++) {

			for (int y = 0; y < mapSize.y; y ++) {

				Vector3 tilePosition = CoordToPosition(x,y);

				Transform newTile = Instantiate (tilePrefab, tilePosition, Quaternion.Euler (Vector3.right * 90)) as Transform;

				newTile.localScale = Vector3.one * (1 - outlinePercent) * tileSize;

				newTile.parent = mapHolder;


			}


		}

		/*int obstacleCount = 10;

		for (int i =0; i < obstacleCount; i ++) {

			Coord randomCoord = GetRandomCoord();

			Vector3 obstaclePosition = CoordToPosition(randomCoord.x,randomCoord.y);

			Transform newObstacle = Instantiate(navPrefab, obstaclePosition + Vector3.up * .5f, Quaternion.identity) as Transform;

			newObstacle.parent = mapHolder;
		}*/



	}
开发者ID:Baranzo94,项目名称:HNR,代码行数:60,代码来源:tileMap.cs


示例18: MmfReader

        /// <summary>
        /// Instantiates MmfReader.
        /// </summary>
        /// <param name="ipcType">Identifies memory mapped file and used to authenticate incoming data.</param>
        /// <param name="bufferLength">Length of data segment</param>
        /// <param name="ignoreExceptions">True if exceptions should be handled; false if they should be thrown to caller</param>
        public MmfReader(string ipcType, int bufferLength, Niawa.Utilities.UtilsServiceBus utilsBus, bool ignoreExceptions)
        {
            try
            {
                _receiveQueue = new Queue<NiawaMmfContainer>();

                _ipcType = ipcType;
                _description = "MmfReader " + _ipcType;
                _bufferLength = bufferLength;
                _ignoreExceptions = ignoreExceptions;

                _lastMsgID = 0;
                _threadStatus = new Niawa.Threading.ThreadStatus(_description, 60, utilsBus.InitializeSerialId(Niawa.Utilities.IdGeneratorUtils.ID_ROOT_NIAWA_THREAD_ID).ToString(), string.Empty, null);

                //thread status
                _threadStatus.Status = Niawa.Threading.ThreadStatus.STATUS_INITIALIZED;

            }
            catch (Exception ex)
            {
                logger.Error("[" + _description + "-M] Exception while instantiating: " + ex.Message, ex);
                if (!ignoreExceptions)
                    throw ex;
            }
        }
开发者ID:nickw4827,项目名称:NiawaNotify,代码行数:31,代码来源:MmfReader.cs


示例19: SetMessageOrder

        private Queue<Message> SetMessageOrder(IEnumerable<Message> unorderedMessages)
        {
            var messages = new Queue<Message>(
                unorderedMessages.OrderBy(x => x.MessengerOrderId));

            return messages;
        }
开发者ID:billboga,项目名称:dnxflash,代码行数:7,代码来源:QueueMessenger.cs


示例20: GlobalCacheEntity

 public GlobalCacheEntity()
 {
     _readCount = 0;
     _lock = Lock.None;
     _isDeleted = false;
     _blockThreads = new Queue<Thread>();
 }
开发者ID:phospher,项目名称:SchoolEndORM,代码行数:7,代码来源:GlobalCacheEntity.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# QueueClient类代码示例发布时间:2022-05-24
下一篇:
C# Question类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap