将多个params数组传递给方法

时间:2014-02-17 08:06:31

标签: c# linq entity-framework repository-pattern

我有GenericRepository这个函数:

public virtual IEnumerable<TEntity> Get(
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    int? Page=0,
    params Expression<Func<TEntity, bool>>[] filter)
{
    IQueryable<TEntity> query = dbSet;

    if (filter != null)
    {
        foreach (var z in filter)
        {
            query = query.Where(z);
        }

    }
    if (orderBy != null)
    {
        return orderBy(query).ToList();
    }
    else
    {
        return query.ToList();
    }
}

在我的一个控制器中,我还需要使用include子句,所以我决定创建新的类DeviceInstanceRepository,它将继承GenericRepository并创建新的GetFiltered方法,我得到这样的结果:

public IEnumerable<DeviceInstance> GetFiltered(
    Func<IQueryable<DeviceInstance>, IOrderedQueryable<DeviceInstance>> orderBy = null, 
    int? Page = 0, 
    **WhatTypeShouldIUSeHere?** System.Linq.Expressions.Expression<Func<DeviceInstance,bool>>[] include ,
    params System.Linq.Expressions.Expression<Func<DeviceInstance, bool>>[] filter)
{
    IQueryable<DeviceInstance> query = dbSet;

    if(include!=null)
    {
        foreach(var z in include)
        {
            query = query.Include(z);
        }
    }
    if (filter != null)
    {
        foreach (var z in filter)
        {
            query = query.Where(z);
        }
    }
    if (orderBy != null)
    {
        return orderBy(query).ToList();
    }
    else
    {
        return query.ToList();
    }
}

但我的参数类型有问题。 我知道我不能通过两个params数组。你能建议我如何修改这一行:

params System.Linq.Expressions.Expression<Func<DeviceInstance,bool>>[] include ,

使事情有效?

1 个答案:

答案 0 :(得分:1)

我不确定您使用此方法尝试实现的目标,但如果您强烈希望在方法中传递两个params参数,则可以将它们合并为一个params,只需要也传递其中一个的数量。像这样(注意TakeSkip):

    public IEnumerable<DeviceInstance> GetFiltered(
        Func<IQueryable<DeviceInstance>, IOrderedQueryable<DeviceInstance>> orderBy = null, 
        int? Page = 0,
        int numberOfIncludeExpressions = 0,
        params System.Linq.Expressions.Expression<Func<DeviceInstance, bool>>[] expressions)
    {
        IQueryable<DeviceInstance> query = dbSet;

        if (expressions != null)
        {
            foreach (var z in expressions.Take(numberOfIncludeExpressions))
            {
                query = query.Include(z);
            }

            foreach (var z in expressions.Skip(numberOfIncludeExpressions))
            {
                query = query.Where(z);
            }
        }
        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }