akd
akd

Reputation: 6758

Is there a better way of shortening this LINQ statement?

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

Answers (3)

Tim Schmelter
Tim Schmelter

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

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

filteredItemNumber =
                this._objectsRep.Find(
                    r =>
                    r.ObjectTitle.StartsWith(searchTerm??"") && r.CreatedDate >= timePeriod.Start
                    && r.CreatedDate <= timePeriod.End).Count();

Upvotes: 1

Paolo Tedesco
Paolo Tedesco

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

Related Questions