使用LINQ得到一个集合的最后N个元素? [英] Using Linq to get the last N elements of a collection?

查看:384
本文介绍了使用LINQ得到一个集合的最后N个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个集合,有没有办法让该集合的最后N个元素?如果没有在框架的方法,这将是编写扩展方法来做到这一点的最好方法是什么?


解决方案

  collection.Skip(Math.Max​​(0,collection.Count() -  N));

此方法preserves项目为了不会对任何排序的依赖,并拥有跨多个LINQ提供广泛的兼容性。

要注意不要叫跳过与负数是很重要的。当$ P $带负参数psented一些供应商,如实体框架,将产生一个ArgumentException。到 Math.Max​​ 的调用避免了这种整齐。

下面的类有所有必需品扩展方法,它们是:静态类,静态方法,并使用这个关键字

 公共静态类MiscExtensions
{
    //例如:collection.TakeLast(5);
    公共静态的IEnumerable< T> TakeLast< T>(这个IEnumerable的< T>源,INT N)
    {
        返回source.Skip(Math.Max​​(0,source.Count() - N));
    }
}

对性能的简要说明:

由于调用计数()可能会导致某些数据结构的枚举,这种方法有导致在数据两遍的风险。这是不是真的大多数枚举接口问题;事实上,已经存在优化的列表,数组,甚至EF查询评估计数()在O(1)时间的操作。

如果,但是,你必须使用只进枚举,并想避免两遍,考虑喜欢的拉塞五卡尔森马克拜尔斯形容。这两种方法都使用一个临时缓冲区,以存放在枚举项,一旦集合的末尾被发现它们产生

Given a collection, is there a way to get the last N elements of that collection? If there isn't a method in the framework, what would be the best way to write an extension method to do this?

解决方案

collection.Skip(Math.Max(0, collection.Count() - N));

This approach preserves item order without a dependency on any sorting, and has broad compatibility across several LINQ providers.

It is important to take care not to call Skip with a negative number. Some providers, such as the Entity Framework, will produce an ArgumentException when presented with a negative argument. The call to Math.Max avoids this neatly.

The class below has all of the essentials for extension methods, which are: a static class, a static method, and use of the this keyword.

public static class MiscExtensions
{
    // Ex: collection.TakeLast(5);
    public static IEnumerable<T> TakeLast<T>(this IEnumerable<T> source, int N)
    {
        return source.Skip(Math.Max(0, source.Count() - N));
    }
}

A brief note on performance:

Because the call to Count() can cause enumeration of certain data structures, this approach has the risk of causing two passes over the data. This isn't really a problem with most enumerables; in fact, optimizations exist already for Lists, Arrays, and even EF queries to evaluate the Count() operation in O(1) time.

If, however, you must use a forward-only enumerable and would like to avoid making two passes, consider a one-pass algorithm like Lasse V. Karlsen or Mark Byers describe. Both of these approaches use a temporary buffer to hold items while enumerating, which are yielded once the end of the collection is found.

这篇关于使用LINQ得到一个集合的最后N个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆