Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 743
MicroMan Avatar asked Aug 27 '13 08:08

MicroMan


2 Answers

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();

like image 111
xanatos Avatar answered Nov 07 '22 01:11

xanatos


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

like image 21
Ronak Patel Avatar answered Nov 07 '22 00:11

Ronak Patel