Splendor
Splendor

Reputation: 1396

Linq query that returns all records if the search item is null or empty

I'm not very well versed in linq and I'm trying to eliminate the need to duplicate a bunch of linq queries in my code. I'm hoping that I can modify this linq query to return a full page of results if the value of the string description is null or empty. Currently it returns no results in that scenario.

So basically I want this query...

return _entities.Schedules.Where(s => s.Description.ToLower().Contains(description.ToLower())))
                        .OrderByWithDirection(x => x.Description, dir)
                        .Skip((pageNumber - 1) * pageSize)
                        .Take(pageSize)
                        .ToList();

...to also return the results that this query would if description were null or empty.

return _entities.Schedules.OrderByWithDirection(x => x.Description, dir)
                            .Skip((pageNumber - 1) * pageSize)
                            .Take(pageSize)
                            .ToList();

Upvotes: 2

Views: 3357

Answers (1)

Jon
Jon

Reputation: 437376

LINQ is composable, so you can very simply do this:

IQueryable<Schedule> results = _entities.Schedules;

// Only filter on description if a search term has been given
if (!string.IsNullOrEmpty(description)) {
    results = results.Where(s => 
                  s.Description.ToLower().Contains(description.ToLower())))
}

return results.OrderByWithDirection(x => x.Description, dir)
              .Skip((pageNumber - 1) * pageSize)
              .Take(pageSize)
              .ToList();

Upvotes: 5

Related Questions