Let's say I have a sequence.
IEnumerable<int> sequence = GetSequenceFromExpensiveSource();
// sequence now contains: 0,1,2,3,...,999999,1000000
Getting the sequence is not cheap and is dynamically generated, and I want to iterate through it once only.
I want to get 0 - 999999 (i.e. everything but the last element)
I recognize that I could do something like:
sequence.Take(sequence.Count() - 1);
but that results in two enumerations over the big sequence.
Is there a LINQ construct that lets me do:
sequence.TakeAllButTheLastElement();
If you can get the
Count
orLength
of an enumerable, which in most cases you can, then justTake(n - 1)
Example with arrays
Example with
IEnumerable<T>
A slight variation on the accepted answer, which (for my tastes) is a bit simpler:
I don't think it can get more succinct than this - also ensuring to Dispose the
IEnumerator<T>
:Edit: technically identical to this answer.