将sql转换为LINQ TOP 1 NOT

时间:2013-03-26 22:28:06

标签: c# sql linq

如何将此SQL转换为LINQ?

Select Top 1 iD, Grad from tbl1 
WHERE tbl1.ID not in 
(Select GradId from tbl2 WHERE ID = 99469)

2 个答案:

答案 0 :(得分:1)

看起来最简单的方法是:

var grads = 
    (from r in tbl2 
     where r.ID == 99469 
     select r.GradID);
var results = 
    (from r in tbl1
     where !grads.Contains(r.ID)
     select new { r.ID, r.Grad })
    .FirstOrDefault();

或者更简洁一点:

var grads = ...
var results = tbl1
    .Select(r => new { r.ID, r.Grad })
    .FirstOrDefault(r => !grads.Contains(r.ID));

答案 1 :(得分:1)

有些内容:

 var query =
         (from c in db.tbl1
          where !(from d in db.tbl2
          select d.id)
               .Contains(c.id)
          select c).Take(1)