How to cast or convert List of objects to queue of objects

流过昼夜 提交于 2019-11-28 09:38:43

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.

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].

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-- )

var mylist = new List<int> {1,2,3};
var q = new Queue<int>(mylist);

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