Create dynamic LINQ expression for Select with FirstOrDefault inside

后端 未结 1 1350
情话喂你
情话喂你 2021-01-16 14:54

I am trying to write this groupQuery:

IQueryable> groupQuery;
...
IQueryable query2 = groupQuery.Select(x         


        
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-16 15:16

    That should do it :

    public IQueryable SelectFirst(IQueryable> groupQuery)
        {
            ParameterExpression param = Expression.Parameter(groupQuery.ElementType, "x");
            var lambda = Expression.Lambda,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(select);
        }
    

    And then you call that as :

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

    0 讨论(0)
提交回复
热议问题