我有一个包含 > 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 是否不为空?
请您参考如下方法:
变量 term 总是有一个值,它永远不会为 null,因为如果查询没有返回结果,那么 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"]);
}
