DataClassesDataContext db = new DataClassesDataContext();
var q = from Blog in db.tblBlogEntries where Blog.ID == EntryID select Blog;
这将仅返回一条记录,因为Blog.ID是主键。
我如何:
答案 0 :(得分:4)
您可以使用SingleOrDefault()
扩展程序。确保检查为null。
var q = (from Blog in db.tblBlogEntries where Blog.ID == EntryID select Blog).SingleOrDefault();
if( q != null)
{
}
答案 1 :(得分:3)
var data = q.FirstOrDefault(); // Or use SingleOrDefault if you want it to throw an error when the result has more than one element.
if (data == null )
// Your query did not match any elements
else
// The result element is in data variable.
答案 2 :(得分:2)
查看有关从Linq查询中检索一个元素的this answer。
(我想你会想要使用SingleOrDefault
方法。)