为什么IEnumerable<;对象>;LINQ查询后不为null
本文关键字:null 查询 gt IEnumerable lt 对象 为什么 LINQ | 更新日期: 2023-09-27 18:23:48
我有一个包含>10000个项目的列表。我正在对这个进行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)总是而不是null!我有一种感觉,只有当我试图访问IEnumerable中的单个对象时,才会执行查询。这是正确的吗?如果是,我该如何检查我的IEnum可耕性是否为空?
变量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"]);
}