0

I have a class

class MyClass
{
  string Foo { get; set; }
  int Bar { get; set; }
  //... Other properties
}

Now what I have is two expressions

Expression<Func<MyClass, string>> expr1 = x => x.Foo;
Expression<Func<MyClass, bool>> expr2 = x => x.Bar > 0;

Using this two expressions, I want to create an expression which is something like this

Expression<Func<MyClass, object>> expr = x => new { Foo = x.Foo, Baz = x.Bar > 0 };

In other words I want to combine two properties into one anonymous object using expression trees. My problem is, How do I create a similar expression from the given two expressions?

I want to use final expression in a join statement with entity framework query. The bool part is complex and need to generate dynamically. If any alternative idea to this, that would be helpful too.

  • Why do you want to do this? (If this is for Entity Framework then be aware that EF/EF-Core only supports a small subset of possible `Expression<>` types with `IQueryable`). – Dai Oct 01 '21 at 08:50
  • Yes, It is for entity framework. Actually x.Bar > 0 is very complex expression in real scenario. My idea is to construct an expression for a Join statement, because condition is complex – Rudrik Andharia Oct 01 '21 at 08:58
  • I don't think that will work at all, simply due to limitations inherent in EF. – Dai Oct 01 '21 at 09:00
  • This is easily done in C# but if it is for EF then the question has to say that. – Lasse V. Karlsen Oct 01 '21 at 09:05
  • I've edited question to mention entity framework – Rudrik Andharia Oct 01 '21 at 09:13
  • Do you know that JOIN can be expressed by `SelectMany`? – Svyatoslav Danyliv Nov 26 '21 at 15:02
  • Thank you guys for your comments. I got support from this answer [https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool#answer-457328](https://stackoverflow.com/questions/457316/combining-two-expressions-expressionfunct-bool#answer-457328) – Rudrik Andharia Nov 30 '21 at 10:01

0 Answers0