Linq查询,如果搜索项为null或为空,则返回所有记录

Spl*_*dor 1 c# linq

我不太熟悉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();
Run Code Online (Sandbox Code Playgroud)

...还返回此查询如果description为null或为空的结果.

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

Jon*_*Jon 5

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();
Run Code Online (Sandbox Code Playgroud)