Convert IQueryable<> type object to List type?

前端 未结 5 1776
广开言路
广开言路 2020-12-02 22:02

I have IQueryable<> object.

I want to Convert it into List<> with selected columns like new { ID = s.ID, Name = s.Name }<

5条回答
  •  孤街浪徒
    2020-12-02 22:51

    Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.

    The positive sides of this approach are:

    • it requires almost no code to use - a simple call to .Transform() is all you need
    • it works just like .Select(s=>new{...}) i.e. when used with IQueryable it produces the optimal SQL code, excluding Type1 fields that DtoType doesn't have.

    LinqHelper.cs:

    public static IQueryable Transform(this IQueryable source)
    {
        var resultType = typeof(TResult);
        var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);
    
        ParameterExpression s = Expression.Parameter(source.ElementType, "s");
    
        var memberBindings =
            resultProperties.Select(p =>
                Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType();
    
        Expression memberInit = Expression.MemberInit(
            Expression.New(typeof(TResult)),
            memberBindings
            );
    
        var memberInitLambda = Expression.Lambda(memberInit, s);
    
        var typeArgs = new[]
            {
                source.ElementType, 
                memberInit.Type
            };
    
        var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);
    
        var query = source.Provider.CreateQuery(mc);
    
        return query;
    }
    
    public static IEnumerable Transform(this IEnumerable source)
    {
        return source.AsQueryable().Transform();
    }
    

提交回复
热议问题