Reputation: 6758
var filteredItemNumber = 0;
if (!string.IsNullOrEmpty(searchTerm))
{
filteredItemNumber =
this._objectsRep.Find(
r =>
r.ObjectTitle.StartsWith(searchTerm) && r.CreatedDate >= timePeriod.Start
&& r.CreatedDate <= timePeriod.End).Count();
}
else
{
filteredItemNumber =
this._objectsRep.Find(t => t.CreatedDate >= timePeriod.Start && t.CreatedDate <= timePeriod.End)
.Count();
}
I am sure there must be a shorten way to get rid of the if statement but I cannot figure it out how. when I use the following code the filtering returns different result than what I am expecting. Maybe the parentheses are not in right place ?
this._objectsRep.Find(r =>
searchTerm == null || r.ObjectTitle.StartsWith(searchTerm) && r.CreatedDate >= timePeriod.Start
&& r.CreatedDate <= timePeriod.End).Count()
What I am trying to achieve is that if the serchTerm is empty or null just ignore that filter but use the date range only.
Thanks
Upvotes: 2
Views: 104
Reputation: 460158
You don't need List.Find
which returns a new list, you can use LINQ to count:
int filteredItemNumber = _objectsRep.Count(r =>
(string.IsNullOrEmpty(searchTerm) || r.ObjectTitle.StartsWith(searchTerm))
&& r.CreatedDate >= timePeriod.Start
&& r.CreatedDate <= timePeriod.End);
Upvotes: 3
Reputation: 11025
filteredItemNumber =
this._objectsRep.Find(
r =>
r.ObjectTitle.StartsWith(searchTerm??"") && r.CreatedDate >= timePeriod.Start
&& r.CreatedDate <= timePeriod.End).Count();
Upvotes: 1
Reputation: 57202
I think you just need to wrap the searchTerm condition like this:
this._objectsRep.Find(r =>
(string.IsNullOrEmpty(searchTerm) || r.ObjectTitle.StartsWith(searchTerm))
&& r.CreatedDate >= timePeriod.Start
&& r.CreatedDate <= timePeriod.End).Count()
Upvotes: 1