Search code examples
c#linqqueue

How To Convert Queue ToList() in C#


I am trying to convert queue to ToList() but in my visual studio it not showing ToList() method to convert Here LoggingQueue.ToList();

Can any one tell me why i am unable to see .ToList() in visual studio.

using System.Linq;
    
static Queue LoggingQueue = new Queue(queueInitialCapacity);
List<test.Client> list = new List<>
public void ReadFromQueue()
{
    List<LogRecord> list = new List<LogRecord>();            
    LogRecord logRecord = null;
    var queueReadRetryCount = 0;
    while (true)
    {
        while (token.IsCancellationRequested)
        {
            break;
        }
        lock (Objlock)
        {
            if (LoggingQueue != null && LoggingQueue.Count > 0)
            {
                lock (LoggingQueue)
                {
                    if (LoggingQueue.Count > 0)
                    {
                        // Start Need to convert Que to List here.
                        var list =  LoggingQueue.ToList();
    
                        // End Need to convert Que to List here.
                        logRecord = LoggingQueue.Dequeue() as LogRecord;
                    }
                }                         
                if (logRecord != null)
                {
                    ProcessQueue(logRecord);
                }
            }
            else
            {
                if (queueInitialCapacity == queueReadRetryCount++)
                {
                    Thread.Sleep(6000);
                    queueReadRetryCount = 0;
                }
            }
        }
    }
    // ReSharper disable once FunctionNeverReturns
}

Solution

  • You can either use generic Queue<T> instead of Queue (better way):

    using System.Collections.Generic;
    
    ...
    
    // Note Queue<LogRecord> instead of Queue
    static Queue<LogRecord> LoggingQueue = new Queue<LogRecord>(queueInitialCapacity);
    
    ...
    
    // Now Linq is posssible since 
    // LoggingQueue implements IEnumerable<LogRecord>
    var list = LoggingQueue
       // You may want to add more Linq here
      .ToList();
    

    Or (if you have to keep Query) add .OfType<LogRecord>() to have IEnumerable<LogRecord> to be queried by Linq:

    // Obsolete Queue from System.Collections
    // it doesn't implement IEnumerable<T>
    static Queue LoggingQueue = new Queue(queueInitialCapacity);
    
    ...
    
    var list = LoggingQueue
      .OfType<LogRecord>() // from now on you have IEnumerable<LogRecord>
       // You may want to add more Linq here
      .ToList();
    

    Please note, that if you want to use queue in a multithread routine (there is a lock in your code) you may want to put

    using System.Collections.Concurrent;
    
    ...
    
    static ConcurrentQueue<LogRecord> LoggingQueue = 
      new ConcurrentQueue<LogRecord>(queueInitialCapacity);
    
    ...