Get rows that come alphabetically after one with a specified ID

断了今生、忘了曾经 提交于 2019-12-11 02:04:58

问题


I'm using .NET Core 1.1, EF Core 1.1.

I have a Category object that I'm querying to do pagination. My function receives the ID of the last object that the front-end parsed, then I need to get the next X objects. I'm sorting alphabetically, however, and I'm not sure how to get the objects that come alphabetically after the object with the given ID.

For example, let's say I have this in my DB:

ID | Name
---|-----
 1 | Sports
 2 | Music
 3 | Books
 4 | TV Shows

For simplicity, we'll say I only want two results per page. My front-end will pass in ID 2 to indicate Music is the latest object the site is showing, and it wants the next two alphabetically. So, I need to return the objects with ID 1 and 4, in that order, because their names are the next two alphabetically. If I passed in ID 3, I would want the results to be 2 and 1.

How can I accomplish this with EF? I feel like this should be very simple but I can't figure it out.


回答1:


Assuming Name is unique, you'll need two queries: one to get the corresponding Name for the passed ID and then use it as a parameter for the second query, selecting the items with greater Name, then ordering and taking the desired count:

int lastId = ...;
var lastName = db.Table.Where(e => e.ID == lastId).Select(e => e.Name).FirstOrDefault();
var result = db.Table
    .Where(e => string.Compare(e.Name, lastName) > 0)
    .OrderBy(e => e.Name)
    .Take(2);


来源:https://stackoverflow.com/questions/41107462/get-rows-that-come-alphabetically-after-one-with-a-specified-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!