If you first check if both are null
as a guard condition, then only one of these 3 conditions can be true
so you could change this 3 single if
statements to a if..else if..else
.
if (model.ValidFrom == null && model.ValidTo == null) { return null;}
if (model.ValidFrom != null && model.ValidTo != null)
{
var dateFrom = (DateTime)model.ValidFrom;
var dateTo = (DateTime)model.ValidTo;
dalList = dalList.Where(s =>
DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date
&& DbFunctions.TruncateTime(s.ValidTo) <= dateTo.Date).AsQueryable();
}
else if (model.ValidFrom != null && model.ValidTo == null)
{
var dateFrom = (DateTime)model.ValidFrom;
dalList = dalList.Where(s => DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date).AsQueryable();
}
else
{
var dateTo = (DateTime)model.ValidTo;
dalList = dalList.Where(s => DbFunctions.TruncateTime(s.ValidTo) <= dateTo.Date).AsQueryable();
}
You also could introduce an enum
which defines the type of the query to be performed and a method GetSearchType()
which returns this enum based on the passed in objects.
private enum SearchType
{
None, Between, GreaterThanFrom, LessThanTo
}
private SearchType GetSearchType(object fromDate, object toDate)
{
if (fromDate == null && toDate == null) { return SearchType.None; }
if (fromDate == null) { return SearchType.LessThanTo; }
if (toDate == null) { return SearchType.GreaterThanFrom; }
return SearchType.Between;
}
then you can use a switch..case
like
switch (GetSearchType(model.ValidFrom, model.ValidTo))
{
case SearchType.Between:
//search here
break;
case SearchType.GreaterThanFrom:
//search here
break;
case SearchType.LessThanTo:
//search here
break;
case SearchType.None:
//nothing to do here, you could also skip
break;
}
which is easier to understand. Instead of doing the search at the cases you should for readability consider to extract the searches to separate methods.
Also copy and paste is ok, you should after deleting a line also delete the line break
var dateFrom = (DateTime)model.ValidFrom; dalList = dalList.Where(s => DbFunctions.TruncateTime(s.ValidFrom) >= dateFrom.Date).AsQueryable();
- 50.9k
- 5
- 83
- 177