How to take all but the last element in a sequence using LINQ?

前端 未结 22 1627
南笙
南笙 2020-11-30 02:51

Let\'s say I have a sequence.

IEnumerable sequence = GetSequenceFromExpensiveSource();
// sequence now contains: 0,1,2,3,...,999999,1000000
         


        
22条回答
  •  一个人的身影
    2020-11-30 03:28

    This is a general and IMHO elegant solution that will handle all cases correctly:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class Program
    {
        public static void Main()
        {
            IEnumerable r = Enumerable.Range(1, 20);
            foreach (int i in r.AllButLast(3))
                Console.WriteLine(i);
    
            Console.ReadKey();
        }
    }
    
    public static class LinqExt
    {
        public static IEnumerable AllButLast(this IEnumerable enumerable, int n = 1)
        {
            using (IEnumerator enumerator = enumerable.GetEnumerator())
            {
                Queue queue = new Queue(n);
    
                for (int i = 0; i < n && enumerator.MoveNext(); i++)
                    queue.Enqueue(enumerator.Current);
    
                while (enumerator.MoveNext())
                {
                    queue.Enqueue(enumerator.Current);
                    yield return queue.Dequeue();
                }
            }
        }
    }
    

提交回复
热议问题