tags:

views:

244

answers:

4

Hi,

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?

+4  A: 

Use LINQ to Objects...

var q = new Queue<T>(array.OrderBy(d => d.date));

EDIT: Ops, wrong way around.

Richard
According to this: http://msdn.microsoft.com/en-gb/library/69zckb8z.aspx it takes an IEnumerable<T>.
Richard
+1  A: 

Try this

public static T ArrayToQueue<T>(T[] items) {
  var queue = new Queue<T>();
  Array.ForEach(items, i => queue.Enqueue(i));
  return queue;
}
JaredPar
*reinvents the wheel*
mquander
A: 

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.

LukeH
Are you sure you need to reverse the array?
teedyay
@teedyay, Thanks, corrected! I did actually test this too, just read the results wrong. :(
LukeH
A: 

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.

Allen