Linq查询,如果搜索项为null或为空,则返回所有记录(Linq query that returns all records if the search item is null or empty)
我不太熟悉linq,我正在努力消除在代码中复制一堆linq查询的需要。 我希望如果字符串description值为null或为空,我可以修改此linq查询以返回整页结果。 目前它在该场景中没有返回任何结果。
所以基本上我想要这个查询......
return _entities.Schedules.Where(s => s.Description.ToLower().Contains(description.ToLower()))) .OrderByWithDirection(x => x.Description, dir) .Skip((pageNumber - 1) * pageSize) .Take(pageSize) .ToList();...如果description为null或为空,也返回此查询的结果。
return _entities.Schedules.OrderByWithDirection(x => x.Description, dir) .Skip((pageNumber - 1) * pageSize) .Take(pageSize) .ToList();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();最满意答案
LINQ是可组合的,因此您可以非常简单地执行此操作:
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();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();更多推荐
发布评论