2019-07-21 17:21

C# 讓 Dequeue 更方便的擴充方法

void Main()
{
    var queue = new Queue<int>();

    for (int i = 0; i < 10; i++) { queue.Enqueue(i); }
    string.Join(",", queue).Dump(); /* 0,1,2,3,4,5,6,7,8,9 */


    var take = queue.EnumerateDequeue().Take(4).ToList();
    string.Join(",", take).Dump(); /* 0,1,2,3 */
    string.Join(",", queue).Dump(); /* 4,5,6,7,8,9 */


    var take2 = queue.EnumerateDequeue().Take(40).ToList();
    string.Join(",", take2).Dump(); /* 4,5,6,7,8,9 */
    string.Join(",", queue).Dump(); /* */
}



public static class QueueExtensions
{

   public static IEnumerable<T> EnumerateDequeue<T>(this Queue<T> source)
   {
       while (source.Count > 0) { yield return source.Dequeue(); }
   }

   public static IEnumerable<T> EnumerateDequeue<T>(this ConcurrentQueue<T> source)
   {
       T outValue;
       while (source.TryDequeue(out outValue)) { yield return outValue; }
   }

}

0 回應: