注意:我错过了您的问题标题“ 使用Linq”,因此我的答案实际上并未使用Linq。
如果要避免缓存整个集合的非惰性副本,则可以编写一个使用链接列表执行此操作的简单方法。
以下方法将在原始集合中找到的每个值添加到链接列表中,并将链接列表缩小为所需的项目数。由于它通过遍历整个集合始终将链接列表修剪为该项目数,因此它将仅保留原始集合中最多N个项目的副本。
它不需要您知道原始集合中的项目数,也不需要多次对其进行迭代。
用法:
IEnumerable sequence = Enumerable.Range(1, 10000);
IEnumerable last10 = sequence.TakeLast(10);
...
扩展方式:
public static class Extensions
{
public static IEnumerable TakeLast(this IEnumerable collection,
int n)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (n < 0)
throw new ArgumentOutOfRangeException("n", "n must be 0 or greater");
LinkedList temp = new LinkedList();
foreach (var value in collection)
{
temp.AddLast(value);
if (temp.Count > n)
temp.RemoveFirst();
}
return temp;
}
}