MicroMan MicroMan - 1 month ago 8
C# Question

.Single or Default with condition or Where clause

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?

Answer Source

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