问题
I have an array of items, sorted so that the oldest item is first in the array.
I want to load a queue from the array, such that when I pop the items on the queue the oldest item comes first.
How can I do this?
回答1:
Use LINQ to Objects...
var q = new Queue<T>(array.OrderBy(d => d.date));
EDIT: Ops, wrong way around.
回答2:
You want a priority queue. Then it doesn't matter whether your incoming items are sorted or not.
Maybe there is an implementation in the library.
PS: the priority in your case would map to age.
回答3:
If you know that your array is already sorted oldest-first then you can use:
Queue<YourType> q = new Queue<YourType>(yourSortedArray);
If the array isn't pre-sorted then you can sort it using LINQ:
Queue<YourType> q =
new Queue<YourType>(yourUnsortedArray.OrderBy(x => x.YourDateProperty));
Then you can just call q.Dequeue to get the items in oldest-to-newest order.
回答4:
Try this
public static T ArrayToQueue<T>(T[] items) {
var queue = new Queue<T>();
Array.ForEach(items, i => queue.Enqueue(i));
return queue;
}
来源:https://stackoverflow.com/questions/561644/queue-ordering