{"id":68988,"date":"2022-04-28T08:23:52","date_gmt":"2022-04-28T06:23:52","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=68988"},"modified":"2022-04-28T08:23:52","modified_gmt":"2022-04-28T06:23:52","slug":"csharp-priority-queue","status":"publish","type":"post","link":"https:\/\/code-maze.com\/csharp-priority-queue\/","title":{"rendered":"Priority Queue in C#"},"content":{"rendered":"<p>Priority Queue in C# is a very useful data structure that has so many real-world applications. In this article, we are going to cover the main concepts of Priority Queue in C#. We have covered the basic <a href=\"https:\/\/code-maze.com\/queue-csharp\/\" target=\"_blank\" rel=\"noopener\">Queue in C#<\/a>, it is recommended to check it out before continuing with this article.\u00a0<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/collections-csharp\/PriorityQueueInCSharp\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s dive in.<\/p>\n<h2>What Is a Priority Queue in C#?<\/h2>\n<p>Priority Queue is just a queue, with a twist. While the dequeuing order in a regular queue depends on the enqueuing precedence &#8211; First In First Out (FIFO), in a priority queue it depends on the priority of the element. In other words, <strong>the element that has the highest priority is dequeued first<\/strong>.\u00a0<\/p>\n<p>Let\u2019s imagine a real-life situation. There are several patients in a hospital queue. Some of these patients are more critical to treat, for example, the elderly. We want to serve these patients before others, whenever they come in. That&#8217;s a scenario when priority queues are handy.<\/p>\n<p>When we add an element, we also specify a priority to indicate how urgently we need to serve it. The element is compared to other elements in the queue and is positioned accordingly, and the element with the highest priority is served first:\u00a0\u00a0<\/p>\n<p><a href=\"https:\/\/code-maze.com\/wp-content\/uploads\/2022\/04\/priority-queue.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-69648 size-full\" src=\"https:\/\/code-maze.com\/wp-content\/uploads\/2022\/04\/priority-queue.jpg\" alt=\"priority queue in C#\" width=\"768\" height=\"410\" srcset=\"https:\/\/code-maze.com\/wp-content\/uploads\/2022\/04\/priority-queue.jpg 768w, https:\/\/code-maze.com\/wp-content\/uploads\/2022\/04\/priority-queue-300x160.jpg 300w\" sizes=\"auto, (max-width: 768px) 100vw, 768px\" \/><\/a><\/p>\n<h2>Basic Priority Queue in C# Example<\/h2>\n<p>Let&#8217;s define our problem by creating the <code>Patient<\/code> class first:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class Patient\r\n{\r\n    public string Name { get; set; } = string.Empty;\r\n    public int Age { get; set; }\r\n\r\n    public Patient(string name, int age)\r\n    {\r\n        Name = name;\r\n        Age = age;  \r\n    }\r\n}\r\n<\/pre>\n<h3>Priority Queue Capacity<\/h3>\n<p>Before we start our solution, let&#8217;s explain the underlying data structure used by <code>PriorityQueue<\/code>. <strong>It stores the elements in an array-backed min-heap, where the root node has the highest priority.<\/strong> The array heap has an initial capacity and when it gets full and we try to enqueue a new element, a new heap is created with a larger capacity. This is what we mean by the priority queue capacity. We will discuss how we can control the capacity in the next section.\u00a0<\/p>\n<h3>Priority Queue Constructors<\/h3>\n<p>Let&#8217;s start our solution by creating an instance of <code>PriorityQueue<\/code>. There is a number of constructors that we can use, let&#8217;s start with the parameterless one:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var hospitalQueue = new PriorityQueue&lt;Patient, int&gt;();\r\nAssert.AreEqual(0, hospitalQueue.EnsureCapacity(0));<\/pre>\n<p>We create a priority queue with zero capacity and demonstrate this by calling the <code>EnsureCapacity<\/code> method. This method takes a number as a parameter and does two things. First, it checks if the queue has enough capacity to contain this number of elements, if not, it expands the capacity of the queue so that it does. Second, the method returns the final capacity. So we can always know the current capacity by calling <code>EnsureCapacity<\/code> and passing <code>0<\/code>\u00a0as an argument.<\/p>\n<p>Alternatively, we can specify an initial capacity when creating the priority queue:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var hospitalQueue = new PriorityQueue&lt;Patient, int&gt;(5);\r\nAssert.AreEqual(5, hospitalQueue.EnsureCapacity(0));\r\nAssert.AreEqual(0, hospitalQueue.Count);<\/pre>\n<p>We notice that the number of elements in the queue is <code>0<\/code>, but there&#8217;s enough memory allocated for <code>5<\/code>\u00a0elements. Initializing a capacity can reduce the number of unnecessary memory reallocations, which can be costly.<\/p>\n<p>Finally, we can just pass our collection of patients and their priorities to the constructor:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patients = new List&lt;(Patient, int)&gt;()\r\n{\r\n    (new(\"Sarah\", 23), 4),\r\n    (new(\"Joe\", 50), 2),\r\n    (new(\"Elizabeth\", 60), 1),\r\n    (new(\"Natalie\", 16), 5),\r\n    (new(\"Angie\", 25), 3)\r\n};\r\nvar hospitalQueue = new PriorityQueue&lt;Patient, int&gt;(patients);\r\nAssert.AreEqual(5, hospitalQueue.EnsureCapacity(0));\r\nAssert.AreEqual(5, hospitalQueue.Count);<\/pre>\n<p>The priority queue allocates just enough memory for the provided list.<\/p>\n<h3>Expanding the Priority Queue Capacity<\/h3>\n<p>We have mentioned that when we add a new element to a full priority queue, the back storage is expanded. So how much more memory is allocated? This is controlled by the growth factor. A growth factor is a number that we multiply by the current capacity to increase it. The growth factor in <code>PriorityQueue<\/code> is two, which means <strong>the capacity is doubled on each expansion<\/strong>. This number is a constant and cannot be changed.<\/p>\n<p>Let&#8217;s enqueue an element to our current priority queue:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">hospitalQueue.Enqueue(new Patient(\"Roy\", 23), 5);\r\nAssert.AreEqual(10, hospitalQueue.EnsureCapacity(0));<\/pre>\n<p>It&#8217;s worth mentioning that the minimum increment is four. Let&#8217;s imagine we have a priority queue with a capacity of one, and we want to add a new element to it. Although we would expect the capacity to be double, which is two. But, this is actually an increment of one, and the minimum allowed increment is four. So, the new capacity would instead be five. The current capacity of one plus the minimum increment of four.<\/p>\n<p>We can increase the capacity manually, by calling <code>EnsureCapacity<\/code> and passing the new number of elements we want to allocate memory for:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Assert.AreEqual(20, hospitalQueue.EnsureCapacity(12));<\/code><\/p>\n<p>Here, we tell the priority queue that we want to allocate memory for <code>12<\/code> elements. The current capacity is <code>10<\/code>. This method follows the same expansion mechanism, but with one further step. It chooses the maximum of two capacities: the specified capacity that we pass as a parameter, and double the current capacity. So, in the above example, we want to allocate memory for <code>12<\/code> patients, but double the current capacity is <code>20<\/code>. So the new capacity is <code>20<\/code>. Let&#8217;s expand our priority queue even more:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">Assert.AreEqual(42, hospitalQueue.EnsureCapacity(42));<\/code><\/p>\n<p>We now want to allocate memory for <code>42<\/code> patients, the current capacity is <code>20<\/code>, so double that is <code>40<\/code>. <code>EnsureCapacity<\/code> chooses the maximum of <code>40<\/code> and <code>42<\/code>.<\/p>\n<h3>Releasing the Unnecessary Memory<\/h3>\n<p>Now we have so much allocated memory, while only having 6 elements in the priority queue. We can release this unnecessary memory by calling <code>TrimExcess<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">hospitalQueue.TrimExcess();\r\nAssert.AreEqual(6, hospitalQueue.EnsureCapacity(0));<\/pre>\n<p>Apart from the capacity, we can use the <code>Clear<\/code> method to remove all the elements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patients = new List&lt;(Patient, int)&gt;()\r\n{\r\n    (new(\"Sarah\", 23), 4),\r\n    (new(\"Joe\", 50), 2),\r\n    (new(\"Elizabeth\", 60), 1),\r\n    (new(\"Natalie\", 16), 5),\r\n    (new(\"Angie\", 25), 3)\r\n};\r\nvar hospitalQueue = new PriorityQueue&lt;Patient, int&gt;(patients);\r\n\r\nhospitalQueue.Clear();\r\n\r\nAssert.AreEqual(5, hospitalQueue.EnsureCapacity(0));\r\nAssert.AreEqual(0, hospitalQueue.Count);<\/pre>\n<p>We notice that the capacity is still the same, this method only clears the priority queue, without any change to its capacity.<\/p>\n<p>Now that we have covered all the creational aspects of our priority queue, let&#8217;s start utilizing it.<\/p>\n<h3>Enqueuing and Dequeueing Priority Queue<\/h3>\n<p>We know that when we enqueue an element in a priority queue we have to specify a priority value for it. In our example, we set the type of the priority type to <code>int<\/code>, so when we add an element we have to provide an integer that represents its priority. <strong>In the C# implementation,<\/strong> <strong>the lowest number has the highest priority<\/strong> (because it&#8217;s actually a min-heap, the root node is the minimum). Let&#8217;s use the <code>Dequeue<\/code> method to dequeue an element from our populated priority queue:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var highestPriorityPatient = hospitalQueue.Dequeue();\r\nAssert.AreEqual(highestPriorityPatient.Age, 60);\r\nAssert.AreEqual(highestPriorityPatient.Name, \"Elizabeth\");<\/pre>\n<p>Having the lowest priority value (being the oldest), Elizabeth has the highest priority and is dequeued first. Now, after Elizabeth has been processed, we expect Joe to be next on the list. Let&#8217;s <code>Peek<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var secondHighestPriorityPatient = hospitalQueue.Peek();\r\nAssert.AreEqual(secondHighestPriorityPatient.Age, 50);\r\nAssert.AreEqual(secondHighestPriorityPatient.Name, \"Joe\");<\/pre>\n<p>We can add new elements to the queue using <code>Enqueue<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">hospitalQueue.Enqueue(new(\"Roy\", 23), 1);\r\nvar currentHighestPriorityPatient = hospitalQueue.Peek();\u00a0\r\nAssert.AreEqual(currentHighestPriorityPatient.Age, 23); \r\nAssert.AreEqual(currentHighestPriorityPatient.Name, \"Roy\");<\/pre>\n<p>We added a new patient, Roy, with the priority <code>1<\/code>, which is currently the lowest priority value in our queue now. Although he is the last in, he is the first out.<\/p>\n<p>Another useful method that we can use to enqueue and dequeue at the same time is <code>EnqueueDequeue<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patientToAdd = new Patient(\"Roy\", 59);\r\nvar highestPriorityPatient = hospitalQueue.EnqueueDequeue(patientToAdd, patientToAdd);\r\n\r\nAssert.AreEqual(highestPriorityPatient.Age, 60);\r\nAssert.AreEqual(highestPriorityPatient.Name, \"Elizabeth\");\r\n\r\nvar secondHighestPriorityPatient = hospitalQueue.Peek();\r\n\r\nAssert.AreEqual(secondHighestPriorityPatient.Age, 59);\r\nAssert.AreEqual(secondHighestPriorityPatient.Name, \"Roy\");<\/pre>\n<p>In the above code, we dequeue the highest priority patient, Elizabeth, and simultaneously enqueue Roy, who&#8217;s now the oldest and the highest priority element.<\/p>\n<h3>Equal Priorities<\/h3>\n<p>We have agreed that the order of processing the elements of the priority queue merely depends on the priority value. But what if the priority values are equal? Do we revert to the queue first-in-first-out basics?<\/p>\n<p>Well, not quite.<\/p>\n<p><strong>In fact, if the priorities are equal among two or more elements, there is no way we can tell which element will be processed first.<\/strong> Let&#8217;s create a new priority queue to demonstrate:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var hospitalQueue = new PriorityQueue&lt;Patient, int&gt;(5);\r\nhospitalQueue.Enqueue(new(\"Sarah\", 23), 1);\r\nhospitalQueue.Enqueue(new(\"Joe\", 50), 1);\r\nhospitalQueue.Enqueue(new(\"Elizabeth\", 60), 1);\r\nhospitalQueue.Enqueue(new(\"Natalie\", 16), 1);\r\nhospitalQueue.Enqueue(new(\"Angie\", 25), 1);\r\n\r\nwhile (hospitalQueue.Count &gt; 0)\r\n    Console.WriteLine(hospitalQueue.Dequeue().Name);<\/pre>\n<p>We gave all the elements the same priority, dequeued them, and wrote them to the console:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Sarah\r\nAngie\r\nNatalie\r\nElizabeth\r\nJoe<\/pre>\n<p>They are not dequeued in the same order they were enqueued. We conclude that, although being a queue, the priority queue has nothing to do with FIFO.<\/p>\n<h2>Implementing a Custom Priority Comparer\u00a0<\/h2>\n<p>In our current implementation, we provided a number for each patient that specifies their priority. We had to make sure we give older patients higher priorities. But what if we can provide our priority queue with some logic that calculates the priority for each patient on the go? We can achieve that by providing the priority queue with an implementation of <code>IComparer<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public class HospitalQueueComparer : IComparer&lt;Patient&gt;\r\n{\r\n    public int Compare(Patient x, Patient y)\r\n    {\r\n        Console.WriteLine($\"Comparing {x.Name} and {y.Name}\");\r\n        Console.WriteLine();    \r\n\r\n        if (x.Age == y.Age)\r\n            return 0;\r\n        else if(x.Age &gt; y.Age)\r\n            return -1;\r\n        else\r\n            return 1;  \r\n    }\r\n}<\/pre>\n<p>We create a class that implements <code>IComparer<\/code>. The <code>Compare<\/code> method compares two patients according to their ages. Remember that in our C# implementation, the less the priority value, the higher the priority. So the method returns:<\/p>\n<ul>\n<li><code>0<\/code> if both patients are the same age<\/li>\n<li><code>-1<\/code> (less than) if <code>x<\/code> is older than <code>y<\/code><\/li>\n<li><code>1<\/code> (greater than) if <code>x<\/code> is younger than <code>y<\/code>\u00a0<\/li>\n<\/ul>\n<p>Now, let&#8217;s provide our priority queue with an instance of this class:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patients = new List&lt;Patient&gt;()\r\n{\r\n    new(\"Sarah\", 23),\r\n    new(\"Joe\", 50),\r\n    new(\"Elizabeth\", 60),\r\n    new(\"Natalie\", 16),\r\n    new(\"Angie\", 25),\r\n};\r\nvar hospitalQueue = new PriorityQueue&lt;Patient, Patient&gt;(new HospitalQueueComparer());\r\npatients.ForEach(p =&gt; hospitalQueue.Enqueue(p, p));<\/pre>\n<p>We make a slight change to our list, it no longer contains priority numbers. We are using the patient object to calculate their priority. Then, we create a priority queue, passing an instance of <code>HospitalQueueComparer<\/code>. Finally, we populate our queue.<\/p>\n<p>Let&#8217;s run the same tests to see if we get the same results:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var highestPriorityPatient = hospitalQueue.Dequeue();\r\nAssert.AreEqual(highestPriorityPatient.Age, 60);\r\nAssert.AreEqual(highestPriorityPatient.Name, \"Elizabeth\");\r\n\r\nvar secondHighestPriorityPatient = hospitalQueue.Peek();\r\nAssert.AreEqual(secondHighestPriorityPatient.Age, 50);\r\nAssert.AreEqual(secondHighestPriorityPatient.Name, \"Joe\");<\/pre>\n<p>We see that Elizabeth, the oldest, has the highest priority. Joe who&#8217;s fifty is next on the list. Great! Now we can guarantee that older patients get treated first.<\/p>\n<h3>When Is Priority Calculated?<\/h3>\n<p>Now that we have a custom comparing method, we can know when and how the <code>PriorityQueue<\/code> sorts the elements, by spotting when the <code>Compare<\/code> method runs. Let&#8217;s make some changes to the <code>Compare<\/code> method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-highlight=\"3-4\">public int Compare(Patient x, Patient y)\r\n{\r\n    Console.WriteLine($\"Comparing {x.Name} and {y.Name}\\n\\r\");\r\n\r\n    if (x.Age == y.Age)\r\n        return 0;\r\n    else if(x.Age &gt; y.Age)\r\n        return -1;\r\n    else\r\n        return 1;  \r\n}<\/pre>\n<p>Let&#8217;s explore the enqueueing operations first:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var patients = new List&lt;Patient&gt;()\r\n    {\r\n        new(\"Sarah\", 23),\r\n        new(\"Joe\", 50),\r\n        new(\"Elizabeth\", 60),\u00a0\r\n        new(\"Natalie\", 16),\r\n        new(\"Angie\", 25),\r\n    };\r\nvar hospitalQueue = new PriorityQueue&lt;Patient, Patient&gt;(new HospitalQueueComparer());\r\npatients.ForEach(p =&gt; {\r\n    Console.WriteLine($\"Enqueueing {p.Name}\"); \r\n    hospitalQueue.Enqueue(p, p);\r\n});<\/pre>\n<p>Now, let&#8217;s check out the output and break it down:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">Enqueueing Sarah\r\nEnqueueing Joe\r\nComparing Joe and Sarah\r\n\r\nEnqueueing Elizabeth\r\nComparing Elizabeth and Joe\r\n\r\nEnqueueing Natalie\r\nComparing Natalie and Elizabeth\r\n\r\nEnqueueing Angie\r\nComparing Angie and Elizabeth<\/pre>\n<p>First, we enqueue Sarah, which is now the only patient in the queue, no need for comparison. Then we enqueue Joe and compare him with Sarah. Now, Sarah is younger, so Joe becomes the root element. Next, we enqueue Elizabeth, she&#8217;s compared with Joe. Elizabeth is older, so she is now the root element.<\/p>\n<p>The last two elements are both compared to Elizabeth, which is the oldest and remains the root element. That&#8217;s it, no more comparisons. So, the <code>PriorityQueue<\/code> instance <strong>makes just enough comparisons to specify the root element<\/strong>. It only knows which element to serve on the next <code>Dequeue()<\/code>\u00a0call.<\/p>\n<p>Now let&#8217;s explore the dequeuing operations:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">...\r\nConsole.WriteLine(\"Dequeuing\");\r\n\r\nwhile (hospitalQueue.Count &gt; 0)\r\n    Console.WriteLine($\"Dequeuing {hospitalQueue.Dequeue().Name}\");<\/pre>\n<p>Let&#8217;s check out the output and break it down as well:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">...\r\nDequeuing\r\nComparing Joe and Sarah\r\n\r\nComparing Natalie and Joe\r\n\r\nComparing Angie and Joe\r\n\r\nDequeuing Elizabeth\r\nComparing Angie and Sarah\r\n\r\nComparing Natalie and Angie\r\n\r\nDequeuing Joe\r\nComparing Natalie and Sarah\r\n\r\nDequeuing Angie\r\nDequeuing Sarah\r\nDequeuing Natalie<\/pre>\n<p>The first thing we notice is that before the first dequeue, all the child elements are compared to each other. We also notice that the comparison logic is similar to the first one, it only aims to find the next highest priority element. Here, it&#8217;s Joe. <strong>So, only now that <\/strong><code>PriorityQueue<\/code> <strong>knows the next element it&#8217;s going to serve, it dequeues Elizabeth.<\/strong> If we continue, we see that the same pattern repeats.<\/p>\n<p>This means that the elements are not stored in an ordered fashion, instead, the <code>PriorityQueue<\/code> only calculates the highest priority element on each enqueuing and dequeuing operation.\u00a0<\/p>\n<h2>Thread Safety of Priority Queue in C#\u00a0<\/h2>\n<p>An instance of <code>PriorityQueue<\/code> is not thread-safe. Although we have a thread-safe implementation of the regular queue in C#: <code>ConcurrentQueue<\/code>, we still don&#8217;t have that for the priority queue. So, if we&#8217;re working in a multithreaded environment, we have to tackle race conditions ourselves when working with <code>PriorityQueue<\/code>.\u00a0<\/p>\n<h2>Conclusion\u00a0\u00a0<\/h2>\n<p>In this article, we have learned how to create a priority queue in C#. We have discussed how we enqueue and dequeued elements, their processing order, and the underlying data structure. Also, we have implemented a custom priority queue with our customer sorting logic, through which we were able to understand the mechanism that the queue uses to achieve its functionality.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Priority Queue in C# is a very useful data structure that has so many real-world applications. In this article, we are going to cover the main concepts of Priority Queue in C#. We have covered the basic Queue in C#, it is recommended to check it out before continuing with this article.\u00a0 Let&#8217;s dive in. [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[12],"tags":[10,946,1232,369],"class_list":["post-68988","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-csharp","tag-net","tag-collections","tag-priority-queue","tag-queue","et_post_format-et-post-format-gallery","et-doesnt-have-format-content"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Priority Queue in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/csharp-priority-queue\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Priority Queue in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/csharp-priority-queue\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-04-28T06:23:52+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Priority Queue in C#\",\"datePublished\":\"2022-04-28T06:23:52+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/\"},\"wordCount\":1809,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\".NET\",\"collections\",\"priority queue\",\"queue\"],\"articleSection\":[\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/csharp-priority-queue\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/\",\"url\":\"https:\/\/code-maze.com\/csharp-priority-queue\/\",\"name\":\"Priority Queue in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-04-28T06:23:52+00:00\",\"description\":\"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/csharp-priority-queue\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/csharp-priority-queue\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Priority Queue in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Priority Queue in C# - Code Maze","description":"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/csharp-priority-queue\/","og_locale":"en_US","og_type":"article","og_title":"Priority Queue in C# - Code Maze","og_description":"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.","og_url":"https:\/\/code-maze.com\/csharp-priority-queue\/","og_site_name":"Code Maze","article_published_time":"2022-04-28T06:23:52+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Priority Queue in C#","datePublished":"2022-04-28T06:23:52+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/"},"wordCount":1809,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":[".NET","collections","priority queue","queue"],"articleSection":["C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/csharp-priority-queue\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/csharp-priority-queue\/","url":"https:\/\/code-maze.com\/csharp-priority-queue\/","name":"Priority Queue in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-04-28T06:23:52+00:00","description":"Priority Queue in C# is a special type of queue where the element that has the highest priority is dequeued first.","breadcrumb":{"@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/csharp-priority-queue\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/csharp-priority-queue\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Priority Queue in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/68988","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=68988"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/68988\/revisions"}],"predecessor-version":[{"id":69868,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/68988\/revisions\/69868"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=68988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=68988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=68988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}