我有一个包含>的列表10.000项。我正在对此进行LINQ查询
IEnumerable<Term> terms = from t in regionCollection
where t.Name == strRegion
select t;
if (terms != null)
{
m.RegId = Convert.ToInt32(terms.FirstOrDefault().CustomProperties["dbId"]);
}
如果(terms!= null)总是不为空!我有一种感觉,只有当我尝试访问IEnumarable中的单个对象时才执行查询。这是正确的,如果是,我如何检查我的IEnumarable是否为空?
答案 0 :(得分:4)
变量term
将始终具有值,它永远不会为空,因为如果查询未返回任何结果,则terms
将为空可枚举。在您的情况下,您可以像这样更新代码:
// Get first item of query or default value
var firstTerm = terms.FirstOrDefault();
// If there were no items, then firstTerm is null
if (firstTerm != null)
{
// This code block is only executed if the query had at least 1 item in results
m.RegId = Convert.ToInt32(firstTerm.CustomProperties["dbId"]);
}