Roby G.
Roby G.

Reputation: 105

FirstOrDefault two ways

I can not understand the difference between these two ways of setting FirstOrDefault:

Product a = (from r in _context.Products where r.IDPROD.Equals(10) select r).FirstOrDefault();
Product a = (from s in _context.Products where s.IDPROD == 10 select s).FirstOrDefault<Products>();

Someone could explain me in a simple way?

Upvotes: 3

Views: 149

Answers (2)

abatishchev
abatishchev

Reputation: 100368

where r.IDPROD.Equals(10) select r).FirstOrDefault();

Method Int32.Equals() used. Then FirstOrdefault<T> where T is detected by compiler automatically (it will be type of r).

where s.IDPROD == 10 select s).FirstOrDefault<Products>()

Operator == overloading used instead. Result forcefully casted to Products.


I would write this using Extension Method syntax:

Product p = _context.Products.FirstOrDefault(p => p.IDPROD == 10);

don't mix it with Query Syntax.

Upvotes: 9

aguyngueran
aguyngueran

Reputation: 1321

It is the same. The first version is FirstOrDefault with inferred generic parameter.

Upvotes: 3

Related Questions