0

Is there a way to add items from a list to a queue without using a loop? The following is the code I currently have:

                    Queue<User> myQueue = new Queue<User>();          
                    List<string> names = new List<string>(){"X", "Y", "Z"};  
          
                    foreach (var name in names)
                    {
                        var response = new User
                        {
                            Name = name,
                            Level = 1
                        };

                        myQueue.Enqueue(response);
                    }
user989988
  • 3,006
  • 7
  • 44
  • 91
  • Any particular reason? – Hans Kesting Dec 09 '21 at 18:47
  • 1
    I think your code is simple and understandable. And it is more or less the same code used by the Queue constructor that receives an IEnumerable. https://referencesource.microsoft.com/#mscorlib/system/collections/queue.cs,75 – Steve Dec 09 '21 at 18:55

3 Answers3

0

You can try creating queue from Linq query:

   using System.Linq;

   ...

   List<string> names = new List<string>(){"X", "Y", "Z"};

   ...

   var myQueue = new Queue<User>(names
     .Select(name => new User() {
        Name = name,
        Level = 1 
      }));

In case you want to enqueue a range of items and you don't want to repeat youself while implementing the loop over and over again; you can write an extension method with a loop:

 public static class QueueExtensions {
   public static void EnqueueRange<T>(this Queue<T> queue, IEnumerable<T> range) {
     if (null == queue)
       throw new ArgumentNullException(nameof(queue));
     if (null == range)
       throw new ArgumentNullException(nameof(range));

     foreach (var item in range)
       queue.Enqueue(item);  
   }
 }  

And use it

     Queue<User> myQueue = new Queue<User>();          
     
     List<string> names = new List<string>(){"X", "Y", "Z"};  
      
     myQueue.EnqueueRange(name.Select(name => new User() {
        Name = name,
        Level = 1 
      })); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You could use the linq foreach, which doesn't look like a loop but it technically is:

names.ForEach(x => myQueue.Enqueue(new User(){Name = name, Level = 1}));
0

You can add them to a new queue:

Queue<AType> ANewQueue = new Queue<AType>(ExistingListOfAType);

And you could do something like:

Queue<AType> AnExistingQueue = new Queue<AType>(RecipeTermsToExclude);
List<AType> AListIWantToAddToThatQueue = new List<AType>(RecipeTermsToExclude);
List<AType> ATempListForTheQueueContents = AnExistingQueue.ToList();
ATempListForTheQueueContents.AddRange(AListIWantToAddToThatQueue);
AnExistingQueue = new Queue<AType>(ATempListForTheQueueContents);
Dronz
  • 1,970
  • 4
  • 27
  • 50