我正在尝试动态创建以下Linq的等效项。
IQueryable<TypeOne> ones;
ones.Select(i => new TypeTwo { TwoProp = i.OneProp });
到目前为止,我有以下代码,但没有。
public class TypeOne
{
public string OneProp { get; set; }
}
public class TypeTwo
{
public string TwoProp { get; set; }
}
public static IQueryable<TypeTwo> Tester(IQueryable<TypeOne> data)
{
ConstructorInfo constructor = typeof(TypeTwo ).GetConstructor(new Type[] { });
Expression body = Expression.New(constructor);
ParameterExpression oneParam = Expression.Parameter(typeof(TypeOne), "one");
Expression prop1 = Expression.Property(oneParam, "OneProp");
ParameterExpression twoParam = Expression.Parameter(typeof(TypeTwo ), "two");
Expression prop2 = Expression.Property(twoParam, "TwoProp");
Expression assign = Expression.Assign(prop2, prop1);
body = Expression.Block(body, assign);
return data.Select(Expression.Lambda<Func<TypeOne, TypeTwo >>(body, oneParam));
}
但是我得到以下异常:
附加信息:类型'System.String'的表达式不能用于返回类型'TypeTwo'
您应该为此使用Expression.MemberInit,如下所示:
public static IQueryable<TypeTwo> Tester(IQueryable<TypeOne> data)
{
var source = Expression.Parameter(typeof(TypeOne), "source");
var selector = Expression.Lambda<Func<TypeOne, TypeTwo>>(
Expression.MemberInit(Expression.New(typeof(TypeTwo)),
Expression.Bind(typeof(TypeTwo).GetProperty("TwoProp"), Expression.Property(source, "OneProp"))),
source);
return data.Select(selector);
}
您可以根据需要包含任意多个Expression.Bind
表达式(即属性分配)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句