linq - 如果where子句不匹配,想用linq返回所有数据
问题描述
我必须使用 startdate 和 enddate 过滤数据。如果没有 startdate 和 enddate,想要返回所有数据,如果开始日期和结束日期不为空,想要使用 linq 返回开始日期和结束日期之间的数据
解决方案
我的建议是为此创建一个扩展方法。
如果您不熟悉扩展方法,请参阅扩展方法揭秘
如果您只将它用于此类,请仅为此类创建扩展方法。如果您打算将其用于“与其他值之间的值”的通用过滤(或只是为了好玩,作为练习),请使用通用方法。
如果没有开始日期和结束日期,想要返回所有数据,如果开始日期和结束日期不为空,想要返回开始日期和结束日期之间的数据
这字面意思是:如果开始日期 == null AND 结束日期 == null,则返回所有日期。否则:返回开始日期和结束日期之间的数据。
需求问题:如果开始日期为空,结束日期不为空,如何返回开始日期和结束日期之间的数据?
唉,你忘了提到有日期的班级,所以让我们假设你有一个查询学生的出生日期:
public static IQueryable<Student> WherBirthDateBetween(
this IQueryable<Student> students,
DateTime? startDate, DateTime? endDate)
{
if (startDate == null)
{
if (endDate == null)
// startDate AND endDate == null: no filtering
return persons;
else
// startDate == null; endDate != null
// requirement problem. Let's assume you want all Students <= endDate
return students.Where(student => student .BirthDay <= endDate.Value);
}
else
{
if (endDate == null)
// startDate != null; endDate == null
// requirement problem. Let's assume you want all students >= startDate
return students.Where(student => student .BirthDay >= startDate.Value);
else
// startDate != null; endDate != null, return where date betweeen:
return students.Where(student => person.BirthDay >= startDate.Value
&& student.BirthDay <= endDate.Value);
}
}
用法:
IQueryable<Student> students = ...
DateTime? startDate = ...
DateTime? endDate = ...
var filteredStudents = students.WhereBirthdayBetween(startDate, endDate)
.ToList();
请注意,由于您的过程在调用 ToList() 之前执行,因此 WhereBirthdayBetween 仅执行一次,即使有数千个学生也是如此。startDate 和 endDate 只计算一次。IQueryable 中的表达式仅更改一次
推荐阅读
- python - Pygame 跳跃动画不起作用 - 虽然走路是
- unity3d - 在 FPS 中应如何以及在何处实例化子弹。统一
- solr - Solr:对嵌套文档使用标记关系会引发未知字段错误
- vue.js - 加载到客户端后刷新静态生成的页面(数据)
- python - 是否可以编写 Python (iOS) 程序来允许/执行对 RaspberryPi 的命令?
- python - Python - 读取音频输入并实时同时播放
- python - 大量数字python的奇怪行为
- jekyll - Jekyll Liquid 标签没有被替换
- c# - 使用另一个类中的方法绘制图形
- html - 按钮 Chrome 周围的白框