如何有条件地将参数传递给func数组

时间:2014-02-14 16:31:12

标签: c# expression method-parameters

我的方法需要以下参数:

public IQueryable<TEntity> GetAllIncluding(params Expression<Func<TEntity, object>>[] includeProperties)
{
    foreach (var includeProperty in includeProperties)
    {
        dbSet.Include(includeProperty);
    }
    return dbSet;
}

这是我如何传递我的参数:

IQueryable<User> users = repo.GetAllIncluding(u => u.EmailNotices, u => u.EmailTemplatePlaceholders, u => u.Actions);

但是,我需要能够在传入之前检查某些条件。

例如,如果我有一个变量useEmailNotices = false,那么我不想传入EmailNotices但是如果它是true那么我就这样做了。我需要为这三个人做这件事。我知道有很长的路要走,但我希望有一条短线路或一条参数构建器功能或者那种性质的东西。

2 个答案:

答案 0 :(得分:3)

如何将方法的签名更改为

public IQueryable<TEntity> GetAllIncluding(IEnumerable<Expression<Func<TEntity, object>>> includeProperties)

在别处定义条件逻辑

var args = new List<Expression<Func<TEntity, object>>>();
if (useEmailNotices)
    args.Add(u => u.EmailNotices);

然后简单地调用类似

的方法
IQueryable<User> users = repo.GetAllIncluding(args);

答案 1 :(得分:2)

使用List<T>代替Params,使用您希望传入的实际实体声明:

var funcList = new List<Expression<Func<User, object>>>();

funcList.add(u => u.EmailTemplatePlaceholders);

if (useEmailNotices)
    funcList.add(u => u.EmailNotices);

方法签名现在是:

public IQueryable<TEntity> GetAllIncluding(List<Expression<Func<TEntity, object>> includeProperties)
{
    foreach( ... )
}