将参数传递给linq谓词

我想编写如下代码:

    public IQueryable<Invoice> InvoiceFilterForMonthAndYear(DateTime? monthAndYear = null)
    {
        var invoices = _invoices.Where(MonthAndYearPredicate(monthAndYear);
        return invoices;
    }

    private bool MonthAndYearPredicate(Invoice invoice, DateTime? monthAndYear)
    {
        //code to check if the invoice start or end dates is from the falls in the month I am checking for
    }

但是我不能使用这样的谓词,因为该谓词只需要一个参数.

我知道我可以在InvoiceFilterForMonthAndYear中编写Where子句来完成工作,但是
我想将比较逻辑放入自己的方法中.

解决方法:

如果您的比较方法返回一个表达式,它将起作用:

private Expression<Func<Invoice,bool>> MonthAndYearPredicate(
    DateTime? monthAndYear)
{
    return i => i.StartDate >= monthAndYear; // or whatever
}

在您的示例中被称为:

var invoices = _invoices.Where(MonthAndYearPredicate(monthAndYear));

或者,您可以将逻辑提取到IQueryable< Invoice>的扩展方法中:

public static class QueryExtensions
{
    public static IQueryable<Invoice> WhereMonthAndYear(
        this IQueryable<Invoice> query, DateTime? monthAndYear)
    {
        return query.Where(i => i.StartDate >= monthAndYear); // or whatever
    }
}

被这样称呼:

var invoices = _invoices.WhereMonthAndYear(monthAndYear);

请记住,在两种情况下,您都必须使用EF可以转换为SQL的有效LINQ-to-Entities表达式.它仅使表达式可重复用于不同的查询,而没有扩展其功能.

上一篇:SpringData_03_Specifications动态查询


下一篇:Python谓词函数名称约定