简体   繁体   English

如何跳过最近2条记录并获取linq的所有其他记录?

[英]How to skip last 2 records and get all other records with linq?

I have a table called Test : 我有一个名为Test的表:

Test: Id, CreatedBy, CreatedDate

Now I want to get list of test but skip last 2 test . 现在我想获得测试列表但skip last 2 test So if I have say for eg 10 test then I want to get 1 - 8 test and skip test 9 and 10 . 因此,如果我对例如10 test说,那么我想得到1-8测试并跳过测试9和10

This is how I am trying to do that: 这就是我试图这样做的方式:

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

In this case: Take(8) 在这种情况下: Take(8)

With Take and Skip you can get any range you want. 使用TakeSkip您可以获得任何您想要的范围。

EG: 例如:

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

Safest way: 最安全的方式:

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

Or you could just do it the other way around (depending on your requirements) 或者你可以反过来做(取决于你的要求)

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

If records size is not fixed, you would use: 如果记录大小未修复,您将使用:

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

or 要么

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.

What you need is very simple, you don't even need to use Take or query the database twice. 你需要的是非常简单的,你甚至不需要使用Take或查询数据库两次。

If you OrderByDescending and Skip the first N elements, then you're taking all the remaining elements by default. 如果您使用OrderByDescendingSkipN个元素,那么默认情况下您将获取所有剩余元素。 So you can just do this: 所以你可以这样做:

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

Docs : 文件

Bypasses a specified number of elements in a sequence and then returns the remaining elements. 绕过序列中指定数量的元素,然后返回其余元素。

If you don't really intend to deffer the execution or append additional querying logic, then calling .ToList() at the end (which actually executes the query against the database) is logical. 如果你真的不打算执行或附加额外的查询逻辑,那么在末尾调用.ToList() (它实际上是对数据库执行查询)是合乎逻辑的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM