c#linq exception:对象引用未设置为对象的实例

Dem*_*ave 3 c# linq exception-handling

当我运行linq查询时,只有在找到项目时才会返回结果; 如果没有找到任何项,则抛出异常"对象引用未设置为对象的实例"

我怎么不抛出这个例外?我只想返回一个结果,即使它是空的.

var id = db.table.Where(a => a.item == passed_item).FirstOrDefault().id;
Run Code Online (Sandbox Code Playgroud)

Chr*_*tos 16

如果未找到对象,则此方法FirstOrDefault将返回null.因此,如果您尝试读取值id,则会抛出异常.

避免这种情况的一种方法如下:

// I suppose that the id you want to read is an int.
// If it isn't, please change the code correspondingly. 
int id;
// Try to get the record.
var record = db.table.Where(a => a.item == passed_item).FirstOrDefault();
// If you find the record you are looking for, then read it's id.
if(record!=null)
    id=record.id;
Run Code Online (Sandbox Code Playgroud)

更新

另一个选择是遵循DavidG他的评论中提出的建议:

var record = db.Table.FirstOrDefault(a => a.item == passed_item);
Run Code Online (Sandbox Code Playgroud)

而下一步是一样的.

  • 或者可能是`db.Table.FirstOrDefault(a => a.item == passed_item)` (5认同)
  • 或者1行`var id =(db.table.FirstOrDefault(a => a.item == passed_item))?. id;` (2认同)