1

I use

ParameterExpression parameter = Expression.Parameter(typeof(T), "p");

var myexp=Expression.Lambda<Func<T, TKey>>(Expression.Property(parameter, "myid"), parameter);

to create a lambda expression myexp like this

p=>myid

now I wanna create a mult property like this

p=> new {myid,myid2}
8
  • 4
    You can just write the lambda you're trying to create and look at it in a debugger to see what expressions it's using, so that you know what you need to create, specifically. Commented Aug 7, 2017 at 20:54
  • Follow this - stackoverflow.com/a/12705338/763026 Commented Aug 7, 2017 at 20:55
  • @Servy I write it for generic class,need to handle propertyName to change Commented Aug 7, 2017 at 21:11
  • @JohnTiXor Okay. That doesn't change my point. Commented Aug 7, 2017 at 21:12
  • I think you mean p => p.myid. Commented Aug 7, 2017 at 21:14

1 Answer 1

3

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 Expressions 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);
Sign up to request clarification or add additional context in comments.

1 Comment

I tried LINQPad and love it, thanks help alot ^ ^,now I use object type to pass anonymous type to do what I want!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.