Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Created May 30, 2022 09:44
Show Gist options
  • Save Sl4vP0weR/818745b4c787aff131fa5c3c06340436 to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/818745b4c787aff131fa5c3c06340436 to your computer and use it in GitHub Desktop.
List with functionality of Queue that allows to enqueue elements in order using Comparison.
/// <summary>
/// <see cref="List{T}"/> with functionality of <see cref="Queue{T}"/> that allows to enqueue elements in order using <see cref="Comparison{T}"/>.
/// </summary>
/// <typeparam name="T">Type of elements.</typeparam>
public class OrderedQueue<T> : List<T>
{
public OrderedQueue(Comparison<T> comparison = null)
{
OrderComparison = comparison ?? ((a, b) => a.Equals(b) ? 0 : -1);
}
public Comparison<T> OrderComparison { get; set; }
public T Peek() => this.FirstOrDefault();
public T Dequeue()
{
var element = Peek();
if (Count > 0)
RemoveAt(0);
return element;
}
public T Enqueue(T element)
{
var index = Count - 1;
for (; index >= 0; index--)
{
if (OrderComparison(this[index], element) >= 0)
break;
}
Insert(Math.Max(index, 0), element);
return element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment