我正在尝试动态创建等同于以下Linq的内容。
到目前为止,我有以下代码,但它还不完整。
然而,我遇到了以下异常 -:
附加信息:类型为'System.String'的表达式不能用作返回类型'TypeTwo'
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'
public class TwoTwo
- 打错了吗? - markpsmithExpression.Lambda<Func<TypeOne, string>>(body, oneParam)
- 但是您的表达式还有其他缺陷(它并不完全符合您要模拟的内容)。 - Rob