經常會看到 使用 FirstOrDefault().字段 獲取對應的值。例如以下代碼:
從數據表集合中取第一行的某個字段值
try
{
IQueryable<Practice> practiceList = GetPracticeByCaseId(caseId);
string temp1 = practiceList.Where(x => x.Id == -1).Select(x=>x.AttendStatus)
.FirstOrDefault();
//故意把條件 id = -1進行篩選使查詢結果為空, temp1 = null , 不會出錯
string temp2 = practiceList.Where(x => x.Id == -1)
.FirstOrDefault()?.AttendStatus;
// temp2 = null,不會出錯
string temp3 = practiceList.Where(x => x.Id == -1)
.FirstOrDefault().AttendStatus;
//這里是會出錯的:Object reference not set to an instance of an object**
。。。。。。
}
catch (Exception e)
{
throw e;
}
注意事項:
用 FirstOrDefault().字段 獲取集合第一行某個字段的值時,要加上?.字段名 以防止 集合為空的情況下出錯。