33

How can one convert a list of objects to a queue thereby maintaining the same order?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
GigaPr
  • 5,206
  • 15
  • 60
  • 77

5 Answers5

61

Queue has a constructor that takes in an ICollection. You can pass your list into the queue to initialize it with the same elements:

var queue = new Queue<T>(list);    // where 'T' is the lists data type.
Ryan Brunner
  • 14,723
  • 1
  • 36
  • 52
  • Good catch. There actually is a non-generic Queue, but you'd likely want the generic version. I've updated my answer. – Ryan Brunner Aug 11 '10 at 23:44
  • @zerkms: There is a non-generic `Queue` class in the `System.Collections` namespace: http://msdn.microsoft.com/en-us/library/system.collections.queue.aspx – Rich Aug 11 '10 at 23:45
  • 1
    But now that you've updated your code example to use `Queue`, your remark that the constructor takes an `ICollection` is no longer accurate (the `Queue` constructor takes an `IEnumerable`). – Dan Tao Aug 12 '10 at 01:35
10

What do you mean by "the same order?"

If you do this:

var queue = new Queue<object>(list);

Then the queue will be enumerated over in the same order as the list, which means that a call to Dequeue would return the element that had previously resided at list[0].

If you do this:

var queue = new Queue<object>(list.AsEnumerable().Reverse());

Then the queue will be enumerated over in the opposite order as the list, which means that a call to Dequeue would return the element that had previously resided at list[list.Count - 1].

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
4
var q = new Queue<Object>();
for( int i = 0; i < list.Count; i++ ) q.Enqueue( list[i] );

That is, assuming "same order" means that the first item to be dequeued from the queue should be list[0].

If it means the opposite, just use the reverse loop: for( int i = list.Count-1; i >= 0; i-- )

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
3

Add this extension to your toolbox to create a FIFO queue of the specific type.

public static class ListExtensions
{
    public static Queue<T> ToQueue<T>(this List<T> items) => new Queue<T>(items);
}
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
2
var mylist = new List<int> {1,2,3};
var q = new Queue<int>(mylist);
zerkms
  • 249,484
  • 69
  • 436
  • 539