如何将IQueryable <t>转换为表达式<func <t,bool =“”>&gt;?</func <t,> </t>

时间:2013-08-22 08:18:17

标签: c# linq expression

我只是想构建一个动态过滤器。 最后回归

 Expression<Func<Event, bool>>

我尝试使用Combine(AndAlso)表达式,但它不起作用,最后我发现有IQueryable查询效果很好,但现在我怎样才能将它转换为返回类型 -

Expression<Func<Event, bool>>?

我的代码:

    public IQueryable<Event> GetBySearch(EventFilter search)
    {
        IQueryable<Event> query = this.Context.Events.AsQueryable();
        Expression<Func<Event, bool>> expression = null;

        if (search.CategoryId != 0)
        {
            query = query.Where(x => x.CategoryId == search.CategoryId);
        }

        if (search.SubCategoryId != 0)
        {
            query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
        }

        expression = query.Expression as Expression<Func<Event, bool>>; //This convert is not working, it returns null.

        return this.Context.Events.Where(expression);
    }

2 个答案:

答案 0 :(得分:7)

任何理由你不要只做以下事情:

public IQueryable<Event> GetBySearch(EventFilter search)
{
    IQueryable<Event> query = this.Context.Events.AsQueryable();

    if (search.CategoryId != 0)
    {
        query = query.Where(x => x.CategoryId == search.CategoryId);
    }

    if (search.SubCategoryId != 0)
    {
        query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
    }

    return query;
}

弗洛里安在评论中说,要避免返回IQueryables(如果可能的话)。简单的解决方案是返回一个列表:

public List<Event> GetBySearch(EventFilter search)
{
    IQueryable<Event> query = this.Context.Events.AsQueryable();

    if (search.CategoryId != 0)
    {
        query = query.Where(x => x.CategoryId == search.CategoryId);
    }

    if (search.SubCategoryId != 0)
    {
        query = query.Where(x => x.SubCategoryId == search.SubCategoryId);
    }

    return query.ToList();
}

答案 1 :(得分:2)

此转换无效,因为Where会将其转换为MethodCallExpression

这是有效的:

MethodCallExpression e = query.Expression as MethodCallExpression;