Create dynamic LINQ expression for Select with FirstOrDefault inside

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

I am trying to write this groupQuery:

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


        
相关标签:
1条回答
  • 2021-01-16 15:16

    That should do it :

    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);
        }
    

    And then you call that as :

    SelectFirst(list.GroupBy(x=>[...]).AsQueryable());
    
    0 讨论(0)
提交回复
热议问题