如何使用 Lambda 从列表中获取最后 x 条记录
我有一个字符串列表,其中我删除了每个重复项,现在我想对其进行更多过滤以获得最后 5 条记录。我该怎么做?
到目前为止我得到了什么
List<string> query = otherlist.Distinct().Select(a => a).ToList();
I have as List of strings with where i remove each duplicates, now I want to filter it even more to get the last 5 records. How can I do this?
What I got so far
List<string> query = otherlist.Distinct().Select(a => a).ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要
.Select(a => a)
。那是多余的。您可以通过跳过其余记录来获取最后 5 条记录,例如
You do not need the
.Select(a => a)
. Thats redundant.You can get the last 5 records, by skipping over the rest like
编辑以满足非列表输入,现在处理
IEnumerable
并检查这是否是IList< /代码>;如果不是,它会通过
ToList()
对其进行缓冲,这有助于确保我们只读取数据一次(而不是.Count()
和.Skip()
可能会多次读取数据)。由于这是一个列表,我倾向于编写一个充分利用它的扩展方法:
edit to cater for non-list inputs, now handles
IEnumerable<T>
and checks if this is anIList<T>
; if not it buffers it viaToList()
, which helps ensure we only read the data once (rather than.Count()
and.Skip()
which may read the data multiple times).Since this is a list, I'd be inclined to write an extension method that uses that to the full:
这个怎么样?
编辑:这就是全部内容 -
另请注意,如果最后有
ToList()
调用,则不应将其称为query
,因为那样它就是 不再是一个查询,它已被评估并变成一个列表。如果您只需要对其进行迭代,则可以省略ToList()
调用并将其保留为IEnumerable
。How about this?
edit: here's the whole thing -
Also note that you shouldn't call it
query
if you've got aToList()
call at the end, because then it's not a query anymore, it's been evaluated and turned into a list. If you only need it to iterate over, you can omit theToList()
call and leave it as anIEnumerable
.编辑:
我错过了数据是 List。这种方法对于 IEnumerable来说会更好。
EDIT:
I missed that the data is List<T> . This approach would be better for IEnumerable<T>