在LINQ to SQL中检索单个记录结果的最佳方法 [英] Best way for retrieving single record results in LINQ to SQL
本文介绍了在LINQ to SQL中检索单个记录结果的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我查询键字段中具有条件的表,如:
If I query a table with a condition on the key field as in:
var user = from u in dc.Users
where u.UserName == usn
select u;
我知道我将得到零个结果或一个结果.我还是应该继续使用for-each检索结果,还是有另一种首选的方式来处理这种情况?
I know that I will either get zero results or one result. Should I still go ahead and retrieve the results using a for-each or is there another preferred way to handle this kind of situation.
推荐答案
尝试如下操作:
var user = (from u in dc.Users
where u.UserName == usn
select u).FirstOrDefault();
FirstOrDefault 方法返回满足条件的序列的第一个元素指定条件或默认值(如果找不到此类元素).
The FirstOrDefault method returns the first element of a sequence that satisfies a specified condition or a default value if no such element is found.
这篇关于在LINQ to SQL中检索单个记录结果的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文