如何跳过最后2条记录,并获得所有其他记录与linq

本文关键字:记录 其他 linq 最后 何跳过 2条 | 更新日期: 2023-09-27 18:04:22

我有一个名为Test的表:

Test: Id, CreatedBy, CreatedDate

现在我想要得到test but skip last 2 test的列表。因此,如果我说例如10 test,那么我想获得1 - 8测试并跳过测试9和10

我是这样做的:

var query = context.Test.OrderByDescending(t=>t.Id).Skip(2) // How to take other records?

如何跳过最后2条记录,并获得所有其他记录与linq

本例中:Take(8)

使用TakeSkip,您可以获得任何您想要的范围。

E。G:

var query = context.Test.OrderByDescending(t=>t.Id);
var allButTheLastTwoElements = query.Take(query.Count() - 2);

安全的方法:

var query = context.Test.OrderByDescending(t=>t.Id).ToList();
var allButTheLastTwoElements = query.Take(Math.Max(0,query.Count() - 2));

或者你可以反过来做(取决于你的要求)

var query = context.Test.OrderByAscending(t=>t.Id).Skip(2);

如果记录大小不固定,则使用:

test.Take(test.Count-2);
//If records are already sorted in the order you like,

test.Where(t=>t.ID <= test.Max(m=>m.ID)-2);
//Where ID is a unique key and the list may not be sorted by id
//This will return the lowest 8 ID even if the list is sorted by address or whatever.

您所需要的非常简单,您甚至不需要使用Take或查询数据库两次。

如果您OrderByDescendingSkip第一个N元素,那么您将默认获取所有剩余的元素。所以你可以这样写:

var query = context.Test.OrderByDescending(t=>t.Id).Skip(2);

文档:

绕过序列中指定数量的元素,然后返回剩余元素

如果您不打算延迟执行或附加额外的查询逻辑,那么在末尾调用.ToList()(它实际上对数据库执行查询)是合乎逻辑的。