Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop the last item with LINQ [duplicate]

Tags:

c#

linq

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.

like image 580
Kei Avatar asked Nov 12 '10 16:11

Kei


People also ask

How do I remove duplicate values in LINQ?

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.

How do you remove the last element in a list in unity?

If you're looking to remove something from the last element of a list, use RemoveAt, and supply it the last index.

How do I find the next record in LINQ?

First(); var next = items . OrderBy(item => item.Id) . First(item => item.Id > currentId); var next = items .

What is skip in LINQ?

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.


2 Answers

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.

like image 110
stakx - no longer contributing Avatar answered Sep 20 '22 06:09

stakx - no longer contributing


someList.Reverse().Skip(1).Reverse() 
like image 31
Saeed Amiri Avatar answered Sep 24 '22 06:09

Saeed Amiri