Sometimes we’ll have an existing sequence of items that we want to prioritize - let’s explore a couple of simple extension methods that can make this easier.
If we already have a queue and want to add many items in one go, it would be useful to have an
EnqueueRange() method. Fortunately, we can write this as a one-liner, using the
Aggregate() function from the LINQ method library:
Admittedly, there’s a lot going on in this “one-line” method. To break it down … we take an existing immutable priority queue (
queue) and use this as the seed for aggregation. The
.Aggregate() extension method iterates through all of the items we want to add (
items), applying the lambda expression to add each value to the queue (
EnqueueRange() defined, we can now define
ToImmutablePriorityQueue(), an extension method on
IEnumerable<T> to turn any sequence into a priority queue. Since we have three different ways to prioritize a queue, we need to provide a trio of implementations:
Each of these starts by creating an empty queue, and then adding in all of the items needed.
Are there any other must have extension methods that we should define?