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

前端 未结 22 1605
南笙
南笙 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:32

    If you can get the Count or Length of an enumerable, which in most cases you can, then just Take(n - 1)

    Example with arrays

    int[] arr = new int[] { 1, 2, 3, 4, 5 };
    int[] sub = arr.Take(arr.Length - 1).ToArray();
    

    Example with IEnumerable

    IEnumerable enu = Enumerable.Range(1, 100);
    IEnumerable sub = enu.Take(enu.Count() - 1);
    

提交回复
热议问题