使用参数过滤IQueryable结果集

时间:2013-05-18 08:02:38

标签: asp.net-mvc linq

我对此感到困惑,我知道会有一种更灵活的启动方式。 'result'变量有很多记录,我想检查IN_SiteId是否为> 0然后对它进行过滤,对于LandownerId和PaymentCategoryId之后也是如此。如果我能够获得前2的正确方法,我将从那里开始。这应该更容易,但有一个砖墙日。任何评论赞赏

public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{

    var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);

    if (IN_SiteId > 0)
    {
        var searchResults = (from s in result
                             where (s.SiteId == @IN_SiteId)
                             select s);

        return searchResults.AsQueryable();
    }

    return result.AsQueryable();
}

1 个答案:

答案 0 :(得分:0)

我不是LINQ专家,但我认为你可以这样做:

public IQueryable rptRentPaidMonthly(int IN_SiteId, int IN_LandownerId, int IN_PaymentCategoryId, int IN_PaymentTypeId, string IN_ShowRelevantProportion)
{
    var result = this._lmsDb.rptRentPaidMonthly(IN_daysFrom, IN_daysTo, IN_SiteId, IN_LandownerId, IN_PaymentCategoryId, IN_PaymentTypeId, IN_ShowRelevantProportion);


    var searchResults = (from s in result
                         where (IN_SiteId <= 0 || s.SiteId == IN_SiteId)
                                && (IN_LandownerId <= 0 || s.LandownerId == IN_LandownerId)
                                && (IN_PaymentCategoryId <= 0 || s.PaymentCategoryId == IN_PaymentCategoryId)
                                && (IN_PaymentTypeId <= 0 || s.PaymentTypeId == In_PaymentTypeId)
                         select s);

    return searchResults.AsQueryable();
}

where子句检查每个过滤器值是否小于或等于0,如果是,则它将返回true,并且不会计算下一个尝试过滤所提供值的实际字段的位。 / p>