如果给出当前记录的ID,这是选择上一条和下一条记录的正确方法吗?

Mad*_*r24 4 c# sql linq entity-framework linq-to-sql

我需要运行一个LINQ查询,它将返回3行(当前记录,上一条记录,以及相对于当前记录的下一条记录.CroductID是我自动生成的标识列.

目前我正在使用Union LINQ语句执行此操作,但我不确定是否有更好或更有效的方法来完成相同的任务.

这是我得到的:

var ProductID = 10;

var Results = (from p in DB.Products
where p.ProductID == ProductID - 1 //Previous record.
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
}).Union(from p in DB.Products
where p.ProductID == ProductID //Current record
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
}).Union(from p in DB.Products
where p.ProductID == ProductID + 1 //Next record.
select new Product
{
    ProductID = p.ProductID,
    ProductTitle = p.ProductTitle,
    Views = p.Views,
});
Run Code Online (Sandbox Code Playgroud)

这应该为ProductID 9,ProductID 10,ProductID 11返回3行.谢谢!

phi*_*ady 6

就个人而言,我会使用这种方法:它有利于在范围内缺少ID的地方工作.一个勇敢的人假设所有的ID都被计算和存在.

 var currAndNext = Context.Set<TPoco>()
                  .Where<TPoco>(t=>t.id == id)
                  .OrderBy(t=>t.id)
                  .Skip(0)
                  .Take(2);
 var prev = Context.Set<TPoco>()
                  .Where<TPoco>(t=>t.id == id)
                  .OrderByDescending(t=>t.id)
                  .Skip(1)
                  .Take(1);
Run Code Online (Sandbox Code Playgroud)

  • 我不明白.首先,在ID列上放置一个where子句(只留下一条记录),然后排序并跳过并取走.那仍然只会让你现在......我错过了什么? (4认同)

TKh*_*ili 3

您的方法可以像这样更简短地重写:

var ProductID = 10;

var Results = (from p in DB.Products
where p.ProductID >= ProductID - 1 &&
      p.ProductID <= ProductID + 1
select new Product
{
   ProductID = p.ProductID,
   ProductTitle = p.ProductTitle,
   Views = p.Views,
});
Run Code Online (Sandbox Code Playgroud)

但请注意,仅当没有从 Products 表中删除与指定的 ProductID 对应的记录时,这才会返回您需要的内容。