Linq查询,如果搜索项为null或为空,则返回所有记录(Linq query that returns all records if the search item is null or empty

编程入门 行业动态 更新时间:2024-10-24 17:34:06
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();

更多推荐

本文发布于:2023-08-04 14:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1417648.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   query   Linq   null   returns

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!