Linq - Where, First, FirstOrDefault

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have the following:

_context.Documents.Where(a => a.Id == id).FirstOrDefault();

Should I use:

_context.Documents.FirstOrDefault(a => a.Id == id);

Or:

_context.Documents.First(a => a.Id == id);

What are the differences?

Thank You,
Miguel
 
shapper said:
I have the following:

_context.Documents.Where(a => a.Id == id).FirstOrDefault();

Should I use:

_context.Documents.FirstOrDefault(a => a.Id == id);

Or:

_context.Documents.First(a => a.Id == id);

What are the differences?

The second code sample is just a shorter way of writing the first code
sample. The third code sample with First(...) will throw an exception if
no such item with a.Id == id is found while FirstOrDefault() does not
throw an exception but returns a default value (e.g. null for reference
types or 0 for int).
 
The second code sample is just a shorter way of writing the first code
sample. The third code sample with First(...) will throw an exception if
no such item with a.Id == id is found while FirstOrDefault() does not
throw an exception but returns a default value (e.g. null for reference
types or 0 for int).

Thank You Martin.
 
Back
Top