通过Id和Name,EF获取下一个和以前的sql行? [英] Get the next and previous sql row by Id and Name, EF?

查看:210
本文介绍了通过Id和Name,EF获取下一个和以前的sql行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在SQL Server表中有以下数据(按名称排序):

Assume we have the following data in a SQL Server table (sorted by name) :

Id   Name        LName
-------------------------
5   Abbas        Dayyan
3   Mohammad     KD
4   Nima         Ahmad
1   Omid         Zangene
2   Pedram       Ahmadi

我们有一个Id查询字符串,我们想得到

we have an Id query string and we wanna get the next and previous row (if exists) from Id.

例如:

Id查询字符串为4 ,所以我们希望将 Mohammad KD 作为上一行,并将 Omid Zangene 作为下一行。

the Id query string is 4, so we wanna get Mohammad KD as previous row and Omid Zangene as next row.

请指教我可以使用LINQ to Entity Framework来实现。

Could you please guide me how can do it with LINQ to Entity Framework.

编辑:

实际上表行数约为100万。

默认情况下,表行没有按排序,唉需要通过Name对其进行排序。


In practice the number of table rows is around 1 million.
Table rows didn't sort by Name by default, wa need to sort them by Name for the result.

推荐答案

这个怎么样?

var result = (from person in db.People
              where person.Id == id
              let ordered = db.People.OrderBy(p => p.Name)                  
              let reversed = db.People.OrderByDescending(p => p.Name)                  
              let previous = reversed.SkipWhile(p => p.Id != id).Skip(1).FirstOrDefault()
              let next = ordered.SkipWhile(p => p.Id != id).Skip(1).FirstOrDefault()
              select new { previous, next }).First();

编辑:考虑到新规范。

编辑2:将代码修改为不使用 LastOrDefault ,这不适用于LINQ to Entities 。

Edit 2: Modified the code to not use LastOrDefault, which doesn't work with LINQ to Entities.

这篇关于通过Id和Name,EF获取下一个和以前的sql行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆