How can I reuse the where condition

Viewed 119

I have a required business logic that should get the product price from the PriceList table. You can see in the code that some parts of the query are repeated.

I'm concerned about how I could reuse some parts of the query: p.Sellers.Any(s => s.PersonId == personID) or currentDate >= p.StartDate && currentDate <= p.EndDate for example.

var basicQuery = context.PriceList.Where(p => !p.Deleted);

// first search by product, salesman and date
var priceItem = basicQuery.FirstOrDefault(p => p.ProductId == productID && 
                                               p.Sellers.Any(s => s.PersonId == personID) &&
                                               currentDate >= p.StartDate &&
                                               currentDate <= p.EndDate);

if(priceItem != null)
   return priceItem;

priceItem = basicQuery.FirstOrDefault(p => p.ProductId == productID && 
                                           currentDate >= p.StartDate &&
                                           currentDate <= p.EndDate);

if(priceItem != null)
   return priceItem;    

priceItem = basicQuery.FirstOrDefault(p => p.ProductId == productID && 
                                           p.Sellers.Any(s => s.PersonId == personID));


if(priceItem != null)
   return priceItem;

priceItem = basicQuery.FirstOrDefault(p => p.ProductId == productID);

return priceItem;
2 Answers
Related