I have the following code
return
this.Storage.Customer.OfType<Preferred>()
.Include(b => b.Order)
.Where(cust => cust.Id == customerId && cust.CustomerType== (int)cusType)
.SingleOrDefault();
It can be rewritten as follows eliminating the where.
return
this.Storage.Customer.OfType<Preferred>()
.Include(b => b.Order)
.SingleOrDefault(cust => cust.Id == customerId && cust.CustomerType == (int)cusType);
Which one is better practice and why?
Thanks to the complexity of debugging the return value of functions, and the impossibility of using lambda expressions in the debugger, this is the best way:
var temp = this.Storage.Customer.OfType<Preferred>()
.Include(b => b.Order)
.Where(cust => cust.Id == customerId && cust.CustomerType == (int)cusType);
return temp.SingleOrDefault();
In this way, if there is an exception on the SingleOrDefault()
(something quite common if you are doing complex expressions), you can put a breakpoint on the return
and do in the watch panel: temp.ToList();
First of all you need to understand the difference
this.Storage.Customer.OfType<Preferred>()
.Include(b => b.Order)
.Where(cust => cust.Id == customerId && cust.CustomerType== (int)cusType)
this will just create a query but will not execute untill you call ToList method.
SingleOrDefault method will actually execute the query. So if you want to check or do something with the query before it is executed you should use where and then call the SingleOrDefault.
so overall, using where is good practice as per my personal opinion
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With