I'm trying to understand how dynamic expressions work. So for learning purposes I'd like to do the following:
I have an object which I can currently access with a Linq statement that uses a lambda expression:
someObj.IncludeStory(x => x.News);
What I'd like to do is replace the labmda x => x.News
with a string, for example:
string myLambda = "x => x.News";
someObj.IncludeStory(myLambda);
Obviously you can't do it like that, but as far as I understand you can achieve somewhat the same with Dynamic Expressions(?).
I've been looking at the System.Linq.Dynamic source code to get an idea of how this should work. But that only confuses me more. I think that library is far to complex for what I want. I don't need sorting, grouping and all that fancy stuff.
Basically my questions are:
- Can I use Dynamic Expressions to generate a lambda like this dynamicaly:
x => x.News
? - If so, then how would I do this with a Dynamic Expression?
I find it hard to get started with this.
What I've tried is something like:
var expression = @"IncludeStory(x => x.News)";
var p = Expression.Parameter(someObj.GetType(), "News");
var e = myAlias.DynamicExpression.ParseLambda(new[] { p }, null, expression);
var result1 = e.Compile().DynamicInvoke(someObj);
delegate
here to achieve the same affect. Correct me if I'm wrong.Where()
,Select()
etc. But I have a custom method calledIncludeStory
. Can I use Dynamic LINQ for that as well?