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

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

    The Enumerable.SkipLast(IEnumerable, Int32) method was added in .NET Standard 2.1. It does exactly what you want.

    IEnumerable sequence = GetSequenceFromExpensiveSource();
    
    var allExceptLast = sequence.SkipLast(1);
    

    From https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skiplast

    Returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted.

提交回复
热议问题