Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 233
Roby G. Avatar asked Sep 08 '26 14:09

Roby G.


1 Answers

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.

like image 151
abatishchev Avatar answered Sep 11 '26 02:09

abatishchev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!