Lea*_*sed 4 c# linq entity-framework
我有一个名为Test的表:
Test: Id, CreatedBy, CreatedDate
Run Code Online (Sandbox Code Playgroud)
现在我想获得测试列表但是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?
Run Code Online (Sandbox Code Playgroud)
Man*_*mer 12
在这种情况下: Take(8)
例如:
var query = context.Test.OrderByDescending(t=>t.Id);
var allButTheLastTwoElements = query.Take(query.Count() - 2);
Run Code Online (Sandbox Code Playgroud)
最安全的方式:
var query = context.Test.OrderByDescending(t=>t.Id).ToList();
var allButTheLastTwoElements = query.Take(Math.Max(0,query.Count() - 2));
Run Code Online (Sandbox Code Playgroud)
或者你可以反过来做(取决于你的要求)
var query = context.Test.OrderByAscending(t=>t.Id).Skip(2);
Run Code Online (Sandbox Code Playgroud)
如果记录大小不固定,您将使用:
test.Take(test.Count-2);
//If records are already sorted in the order you like,
Run Code Online (Sandbox Code Playgroud)
或者
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5552 次 |
| 最近记录: |