为Select with FirstOrDefault创建动态LINQ表达式

时间:2014-02-20 23:44:36

标签: c# .net linq entity-framework

我正在尝试编写这个groupQuery:

IQueryable<IGrouping<TKey, TEntity>> groupQuery;
...
IQueryable<TEntity> query2 = groupQuery.Select(x => x.FirstOrDefault());

作为动态表达式:

ParameterExpression param = Expression.Parameter(typeof(TEntity), "x");

IQueryable<TEntity> query2 = groupQuery.Provider.CreateQuery(
    Expression.Call(
        typeof(Queryable),
        "Select",
        new Type[] { typeof(TEntity), typeof(TKey)},
        groupQuery.Expression,
        Expression.Lambda(firstOrDefaultExpression, param)));

如何编写firstOrDefaultExpression以及如何完成此动态表达式以获得与groupQuery.Select(x => x.FirstOrDefault())相同的结果?

1 个答案:

答案 0 :(得分:1)

应该这样做:

public IQueryable<TEntity> SelectFirst<TEntity,TKey>(IQueryable<IGrouping<TKey, TEntity>> groupQuery)
    {
        ParameterExpression param = Expression.Parameter(groupQuery.ElementType, "x");
        var lambda = Expression.Lambda<Func<IGrouping<TKey, TEntity>,TEntity>>(
            Expression.Call(typeof(Enumerable),"FirstOrDefault",new []{typeof(TEntity)},param), 
            param);

        var select = Expression.Call(
            typeof(Queryable),
            "Select",
            new []{groupQuery.ElementType,typeof(TEntity)},
            groupQuery.Expression,lambda);
        return groupQuery.Provider.CreateQuery<TEntity>(select);
    }

然后你称之为:

SelectFirst(list.GroupBy(x=>[...]).AsQueryable());