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}
John TiXor
  • 73
  • 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. – Servy Aug 07 '17 at 20:54
  • Follow this - https://stackoverflow.com/a/12705338/763026 – Angshuman Agarwal Aug 07 '17 at 20:55
  • @Servy I write it for generic class,need to handle propertyName to change – John TiXor Aug 07 '17 at 21:11
  • @JohnTiXor Okay. That doesn't change my point. – Servy Aug 07 '17 at 21:12
  • I think you mean `p => p.myid`. – NetMage Aug 07 '17 at 21:14
  • You can't create anonymous type at runtime. It's unclear what are you trying to achieve - what will be the type of the result, how it's supposed to be used etc. – Ivan Stoev Aug 07 '17 at 21:17
  • You can actually create anonymous types at runtime, but it is rarely worth it. – NetMage Aug 07 '17 at 21:35
  • @Ivan Stoev actually I can, I use List.AsQueryable().GroupBy(p=>new{p.myid,p.myid2}).Select(p => p.First()) to replace dinstinct(IEqualityComparer),if I can handle expression "p=>new{p.myid,p.myid2}",then no need to repeat create IEqualityComparer anymore. it's also useful to make dynamic query with combination expression – John TiXor Aug 07 '17 at 22:39

1 Answers1

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);
T.S.
  • 18,195
  • 11
  • 58
  • 78
NetMage
  • 26,163
  • 3
  • 34
  • 55
  • I tried LINQPad and love it, thanks help alot ^ ^,now I use object type to pass anonymous type to do what I want! – John TiXor Aug 08 '17 at 12:48