如何使用linq获取有序表的子集中的下一个项目?

时间:2009-04-10 17:48:47

标签: .net sql linq linq-to-sql

我有两张桌子:

Topic (
  TopicID: int, (primary key)
  TopicName: varchar
);

Example (
  ExampleID: int, (primary key)
  TopicID: int, (foreign key to Topic table)
  ExampleOrder: int,
  ExampleName: varchar
);

使用Linq,给定一个ExampleID,我想在同一主题(具有相同的TopicID)中获得下一个示例。以下是在sql中完成的方法:

DECLARE @ExampleOrder int;
DECLARE @TopicID int;
SELECT @ExampleOrder=ExampleOrder, @TopicID=TopicID FROM Example WHERE ExampleID=@ExampleID;
SELECT TOP 1 ExampleID FROM Example WHERE TopicID=@TopicID AND ExampleOrder>@ExampleOrder ORDER BY ExampleOrder

在Linq有一个简单的方法吗?我知道我可以用两个Linq查询来做到这一点,但是我试图在没有额外往返数据库的情况下完成它。

2 个答案:

答案 0 :(得分:2)

int exampleID = 5;
  //now to write a query
var query =
  from ex in db.Examples
  let prior = db.Examples.Where(ex2 => ex2.ExampleID == exampleID).First()
  where ex.TopicID == prior.TopicID
     && ex.ExampleOrder > prior.ExampleOrder
  order ex by ex.ExampleOrder descending
  select ex
    //ok, let's run the query - result will have 0 or 1 item in it.
List<Example> result = query.Take(1).ToList();

答案 1 :(得分:2)

public Example GetNextExample(IEnumerable<Example> examples, Int32 exampleID)
{
   Example example = examples.Single(e => e.ExampleId == exampleID);

   return examples.
      Where(e => e.TopicID == 
         examples.Single(e => e.ExampleId == exampleID).TopicID).
      OrderBy(e => e.ExampleOrder).
      FirstOrDefault(e => e.ExampleOrder > 
         examples.Single(e => e.ExampleId == exampleID).ExampleOrder);
}