Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert List to Queue c# [duplicate]

Tags:

c#

.net

vb.net

is it possible to convert a List to a Queue element?? Until now i used the code below but adding an extra loop is not necessary if there is a build up method in c#

queue1.Clear();

foreach (int val in list1)
{
     queue1.Enqueue(val);
}

any solution?

like image 884
Stavros Afxentis Avatar asked Mar 08 '15 15:03

Stavros Afxentis


1 Answers

Queue<T> has an overload which takes an IEnumerable<T>. Note it will iterate it anyway:

var queue = new Queue<string>(myStringList);

This is what it does internally:

public Queue(IEnumerable<T> collection)
{
    _array = new T[_DefaultCapacity];
    _size = 0;
    _version = 0;

    using(IEnumerator<T> en = collection.GetEnumerator()) 
    {
        while(en.MoveNext()) {
            Enqueue(en.Current);
        }
    }            
}
like image 98
Yuval Itzchakov Avatar answered Sep 28 '22 00:09

Yuval Itzchakov