The tricky part of doing this is accessing the anonymous type's type so you can call new
for it. I normally use LINQPad to create a sample lambda and dump it to see the format:
Expression<Func<Test,object>> lambdax = p => new { p.myid, p.myid2 };
lambdax.Dump();
Assuming the type of p
is Test
:
class Test {
public int myid;
public int myid2;
}
Then you can create Expression
s to recreate the lambdax
value:
var exampleTest = new Test();
var example = new { exampleTest.myid, exampleTest.myid2 };
var exampleType = example.GetType();
var rci = exampleType.GetConstructors()[0];
var parm = Expression.Parameter(typeof(Test), "p");
var args = new[] { Expression.PropertyOrField(parm, "myid"), Expression.PropertyOrField(parm, "myid2") };
var body = Expression.New(rci, args, exampleType.GetMembers().Where(m => m.MemberType == MemberTypes.Property));
var lambda = Expression.Lambda(body, parm);