Drop the last item with LINQ

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()

Tags:

C#

Linq