我需要的是一种从列表中选择最后100个元素的方法,如列表
public List<Model.PIP> GetPIPList()
{
if (Repository.PIPRepository.PIPList == null)
Repository.PIPRepository.Load();
return Repository.PIPRepository.PIPList.Take(100);
}
Run Code Online (Sandbox Code Playgroud)
我得到这样的错误
'System.Collections.Generic.IEnumerable'到'System.Collections.Generic.List'.存在显式转换(您是否错过了演员?)
somelist.Reverse().Take(100).Reverse().ToList();
Run Code Online (Sandbox Code Playgroud)
这将比订购便宜得多:)还保留了原始订购.
如果您的列表很大,那么您可以通过自己的方式获得最佳性能:
public static class ListExtensions
{
public static IEnumerable<T> LastItems<T>(this IList<T> list, int numberOfItems) //Can also handle arrays
{
for (int index = Math.Max(list.Count - numberOfItems, 0); index < list.Count; index++)
yield return list[index];
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这比使用Skip()更快?如果你有一个包含50,000个项目的列表,Skip()会在枚举器上调用MoveNext()49,900次,然后才开始返回项目.
为什么它比使用Reverse()更快?因为Reverse分配一个足够大的新数组来保存列表的元素,并将它们复制到数组中.如果数组足够大以进入大对象堆,则尤其可以避免这种情况.