Using Linq; how can I do the “opposite” of Take?
I.e. instead of getting the first n elements such as in
aCollection.Take(n)
I want to get everything but the last n elements. Something like
aCollection.Leave(n)
(Don’t ask why 🙂
Edit
I suppose I can do it this way aCollection.TakeWhile((x, index) => index < aCollection.Count - n) Or in the form of an extension
public static IEnumerable<TSource> Leave<TSource>(this IEnumerable<TSource> source, int n)
{
return source.TakeWhile((x, index) => index < source.Count() - n);
}
But in the case of Linq to SQL or NHibernate Linq it would have been nice if the generated SQL took care of it and generated something like (for SQL Server/T-SQL)
SELECT TOP(SELECT COUNT(*) -@n FROM ATable) * FROM ATable Or some other more clever SQL implementation.
I suppose there is nothing like it?
(But the edit was actually not part of the question.)
EDIT: Just as a piece of interesting information which came up in the comments – you may think that the
IEnumerable‘s extension method.Count()is slow, because it would iterate through all elements. But in case the actual object implementsICollectionorICollection<T>, it will just use the.Countproperty which should be O(1). So performance will not suffer in that case.You can see the source code of
IEnumerable.Count()at TypeDescriptor.net.