有没有更好的方法来缩短这个LINQ语句?

时间:2014-03-06 11:28:56

标签: c# linq

var filteredItemNumber = 0;
        if (!string.IsNullOrEmpty(searchTerm))
        {
            filteredItemNumber =
                this._objectsRep.Find(
                    r =>
                    r.ObjectTitle.StartsWith(searchTerm) && r.CreatedDate >= timePeriod.Start
                    && r.CreatedDate <= timePeriod.End).Count();
        }
        else
        {
            filteredItemNumber =
                this._objectsRep.Find(t => t.CreatedDate >= timePeriod.Start && t.CreatedDate <= timePeriod.End)
                    .Count();
        }

我确信必须有一个缩短方法来摆脱if语句,但我无法弄清楚如何。当我使用以下代码时,过滤返回的结果与我期望的结果不同。也许括号不在正确的位置?

this._objectsRep.Find(r =>
                searchTerm == null || r.ObjectTitle.StartsWith(searchTerm) && r.CreatedDate >= timePeriod.Start
                && r.CreatedDate <= timePeriod.End).Count()

我想要实现的是,如果serchTerm为空或null,则忽略该过滤器,但仅使用日期范围。

由于

3 个答案:

答案 0 :(得分:3)

您不需要List.Find返回新列表,您可以使用LINQ来计算:

int filteredItemNumber = _objectsRep.Count(r => 
    (string.IsNullOrEmpty(searchTerm) || r.ObjectTitle.StartsWith(searchTerm))
    && r.CreatedDate >= timePeriod.Start 
    && r.CreatedDate <= timePeriod.End);

答案 1 :(得分:1)

我认为您只需要像这样包装searchTerm条件:

this._objectsRep.Find(r =>
    (string.IsNullOrEmpty(searchTerm) || r.ObjectTitle.StartsWith(searchTerm)) 
    && r.CreatedDate >= timePeriod.Start
    && r.CreatedDate <= timePeriod.End).Count()

答案 2 :(得分:1)

filteredItemNumber =
                this._objectsRep.Find(
                    r =>
                    r.ObjectTitle.StartsWith(searchTerm??"") && r.CreatedDate >= timePeriod.Start
                    && r.CreatedDate <= timePeriod.End).Count();