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:

public static IImmutablePriorityQueue<T> EnqueueRange<T>(
    this IImmutablePriorityQueue<T> queue,
    IEnumerable<T> items)
    => items.Aggregate(
        queue,
        (q, i) => q.Enqueue(i));

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 (.Enqueue()).

With 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:

public static IImmutablePriorityQueue<T> ToImmutablePriorityQueue<T>(
    this IEnumerable<T> items,
    IComparer<T> comparer)
    => ImmutablePriorityQueue<T>.Create(comparer)
        .EnqueueRange(items);

public static IImmutablePriorityQueue<T> ToImmutablePriorityQueue<T, K>(
    this IEnumerable<T> items,
    Func<T, K> keySelector)
    => ImmutablePriorityQueue<T>.Create(keySelector)
        .EnqueueRange(items);

public static IImmutablePriorityQueue<T> ToImmutablePriorityQueue<T>(
    this IEnumerable<T> items)
    where T : IComparable<T>
    => ImmutablePriorityQueue<T>.Create<T>()
        .EnqueueRange(items);

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?

Prior post in this series:
Generating Hash Codes
Next post in this series:
Converting a List to a Queue

Comments

blog comments powered by Disqus