John TiXor
John TiXor

Reputation: 73

How can I make a Multiple property lambda expression with Linq

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}

Upvotes: 1

Views: 2612

Answers (1)

NetMage
NetMage

Reputation: 26936

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);

Upvotes: 3

Related Questions