Extracting Func<> from Expression<>
Asked Answered
S

1

11

I wanna extract the Func<> from the following Expression :

Expression<Func<IQueryable<Entity>, IOrderedQueryable<Entity>>> order = q => q.OrderByDescending(c=>c.FullName);

Func<IQueryable<Entity>, IOrderedQueryable<Entity>> orderFunc = ?

How can I do it?

Edit :

And how can we convert Func<IQueryable<Entity>, IOrderedQueryable<Entity>> to Expression<Func<IQueryable<Entity>, IOrderedQueryable<Entity>>> ?

Synthesize answered 4/12, 2013 at 6:33 Comment(3)
orderFunc = order.Compile().Antithesis
@KirillShlenskiy: Please write it to new post form marking as answerSynthesize
Apologies - I didn't have enough time to write up a full answer, but still wanted to help. Servy has already provided an answer which addresses your edit as well as the original question, which is better than what I would have written anyway.Antithesis
P
15

You can use the Compile method to turn any Expresstion<TDelegate> into a TDelegate.


There is no way to convert a delegate into an Expression<TDelegate>. The detailed information about what makes up the expression was lost when it was compiled into a delegate.

You could, in theory create an expression who's body does nothing but invoke the given delegate, by doing something like this:

Func<int> function = () => 42;
Expression<Func<int>> expression = () => function();

but such an expression isn't really useful. There really isn't any meaningful information inside of that expression. So while it's technically possible, it's never really practical.

Pontificals answered 5/12, 2013 at 21:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.