使用Linq; 怎么办Take的"对立面"?
也就是说,而不是获得前面的n个元素
aCollection.Take(n)
Run Code Online (Sandbox Code Playgroud)
我想获得除了最后n个元素之外的所有元素.就像是
aCollection.Leave(n)
Run Code Online (Sandbox Code Playgroud)
(不要问为什么:-)
编辑
我想我可以这样做aCollection.TakeWhile((x, index) => index < aCollection.Count - n)或者以扩展的形式
public static IEnumerable<TSource> Leave<TSource>(this IEnumerable<TSource> source, int n)
{
return source.TakeWhile((x, index) => index < source.Count() - n);
}
Run Code Online (Sandbox Code Playgroud)
但是在Linq to SQL或NHibernate Linq的情况下,如果生成的SQL处理它并生成类似的内容(对于SQL Server/T-SQL)会很好
SELECT TOP(SELECT COUNT(*) -@n FROM ATable) * FROM ATable 或者其他一些更聪明的SQL实现.
我想没有什么比这更好的了吗?(但编辑实际上不是问题的一部分.)
Dmy*_*nko 21
aCollection.Take(aCollection.Count() - n);
Run Code Online (Sandbox Code Playgroud)
编辑:正如评论中提到的一条有趣的信息 - 你可能认为IEnumerable扩展方法.Count()很慢,因为它会迭代所有元素.但如果实际的对象实现ICollection或者ICollection<T>,它只是利用.Count这应该为O特性(1).因此,在这种情况下性能不会受到影响.
您可以IEnumerable.Count() 在TypeDescriptor.net上看到源代码.
Hei*_*nzi 11
我很确定没有内置的方法,但这可以通过链接Reverse和Skip以下方式轻松完成:
aCollection.Reverse().Skip(n).Reverse()
Run Code Online (Sandbox Code Playgroud)