0

在下面,model.Status 和 model.Source 值可能为空,也可能不为空。如果为 null,我希望表达式提取所有状态/来源。这对 lambda 是否可行,因为下面的语句不起作用?

var leads = db.CallCenterLead.Include("Profile").Include("Account")
.Where(x => x.DateSent >= model.DateFrom && x.DateSent <= model.DateTo 
&& ((model.Status != null && x.Status == model.Status) || (model.Status == null)) 
&& (model.Source != null && x.Source == model.Source)).OrderByDescending(x => x.DateSent).ToList();
4

1 回答 1

0

一种方法是使用扩展方法,如下所示:

var leads = db.CallCenterLead.Include("Profile").Include("Account")
    .Where(x => x.DateSent >= model.DateFrom && x.DateSent <= model.DateTo)
    .WhereIf(model.Status != null, x.Status == model.Status)
    .WhereIf(model.Source != null, x.Source == model.Source)
    .OrderByDescending(x => x.DateSent).ToList();

扩展方法:

public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
    return condition ? source.Where(predicate) : source;
}

如果条件为真,该方法添加谓词。否则,它只是按原样返回源。

于 2012-07-25T14:04:52.283 回答