具有可空参数输入的C#Lambda表达式

时间:2012-07-25 12:43:53

标签: linq-to-entities

如下所示,model.Status和model.Source值可能为null,也可能不为null。如果为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();

1 个答案:

答案 0 :(得分: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;
}

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