Queue ordering

倾然丶 夕夏残阳落幕 提交于 2019-12-08 03:23:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!