首页 > 解决方案 > 如果where子句不匹配,想用linq返回所有数据

问题描述

我必须使用 startdate 和 enddate 过滤数据。如果没有 startdate 和 enddate,想要返回所有数据,如果开始日期和结束日期不为空,想要使用 linq 返回开始日期和结束日期之间的数据

标签: 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 中的表达式仅更改一次


推荐阅读