Seems like a trivial task with LINQ (and probably it is), but I cannot figure out how to drop the last item of squence with LINQ. Using Take and passing the length of the sequence – 1 works fine of course. However, that approach seems quite inconvienient when chaining up multiple LINQ in a single line of code.
IEnumerable<T> someList ....
// this works fine
var result = someList.Take(someList.Count() - 1);
// but what if I'm chaining LINQ ?
var result = someList.Where(...).DropLast().Select(...)......;
// Will I have to break this up?
var temp = someList.Where(...);
var result = temp.Take(temp.Count() - 1).Select(...)........;
In Python, I could just do seq[0:-1]. I tried passing -1 to Take method, but it does not seem to do what I need.
For .NET Core 2+ and .NET Standard 2.1 (planned), you can use
.SkipLast(1).For other platforms, you could write your own LINQ query operator (that is, an extension method on
IEnumerable<T>), for example:Unlike other approaches such as
xs.Take(xs.Count() - 1), the above will process a sequence only once.