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.
We can remove all duplicates like this by using GroupBy and Select methods provided by LINQ . First, we group our list so that we will create groups for each name in the List. Then we use Select to only select the first objects in each group. This will result in the removal of the duplicates.
If you're looking to remove something from the last element of a list, use RemoveAt, and supply it the last index.
First(); var next = items . OrderBy(item => item.Id) . First(item => item.Id > currentId); var next = items .
The Skip Method in Linq is used to skip or bypass the first “n” number of elements from a data source or sequence and then returns the remaining elements from the data source as output. Here “n” is an integer value passed to the Skip method as a parameter.
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:
static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source) { using (var e = source.GetEnumerator()) { if (e.MoveNext()) { for (var value = e.Current; e.MoveNext(); value = e.Current) { yield return value; } } } }
Unlike other approaches such as xs.Take(xs.Count() - 1)
, the above will process a sequence only once.
someList.Reverse().Skip(1).Reverse()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With