我正在尝试动态创建以下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'
答案 0 :(得分:3)
您应该使用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
个表达式(即属性分配)。