在 Tim 和 Dipin 的基础上,First()
当查询没有产生任何结果时,该方法不幸地抛出 InvalidOperationException。
要么用 try/catch 块包围它
try{
var latest = (from d in db.CT_Decals
where d.TankID == decal.TankID && d.DecalStatus == "Approved"
orderby d.DecalExpireDate descending
select new
{
d.DecalExpireDate,
d.DecalExpireMonth,
d.DecalExpireYear
}).First();
var decalExpireDate = latest.DecalExpireDate;
var decalExpireMonth = latest.DecalExpireMonth;
var decalExpireYear = latest.DecalExpireYear;
}
catch(InvalidOperationException ex){ // tell no Result!}
或者您可以使用FirstOrDefault()
which 在查询不匹配时返回空引用。
//... Example from above
}).FirstOrDefault();
// check for null-reference
if(latest != null)
var decalExpireDate = latest.DecalExpireDate;
var decalExpireMonth = latest.DecalExpireMonth;
var decalExpireYear = latest.DecalExpireYear;
}
第三种可能性是使用第一个元素Take(1)
//... Example from above
}).Take(1).ToList(); // returns an empty list if no match
// check whether something was returned
if(latest.Any())
var decalExpireDate = latest[0].DecalExpireDate;
var decalExpireMonth = latest[0].DecalExpireMonth;
var decalExpireYear = latest[0].DecalExpireYear;
}