Reputation: 1396
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
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