How to create lambda dynamic expression based on lambda from string in c #?

I'm having difficulty creating Lambda-based Linq expressions from a string. Here is my main example using this sample object / class:

public class MockClass { public string CreateBy { get; set; } } 

Basically I need to convert the string as follows:

 string stringToConvert = "x => x.CreateBy.Equals(filter.Value, StringComparison.OrdinalIgnoreCase"; 

In the expression for the / linq predicate:

 System.Linq.Expressions.Expression<Func<T, bool>> or in this example System.Linq.Expressions.Expression<Func<MockClass, bool>> 

So this is equivalent to the Linq expression inside the Where method below:

 query = query.Where(x => x.CreateBy.Equals(filter.Value, StringComparison.OrdinalIgnoreCase)); 

I tried using the following helpers, but I can’t figure out how to make them work in this type of case when I want to build a linq expression from a string that I don’t know beforehand: http://www.albahari.com/nutshell/predicatebuilder.aspx

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx (now it is available as a NuGet package, also called DynamicQuery)

+2
c # lambda linq expression-trees dynamic-linq
source share
1 answer

A similar question was asked here:

Is there an easy way to parse a string (lambda expression) in the action dellet?

As I understand it, this "dynamic query" is actually the basis for limiting the restrictions for the Where clause without using a lambda expression.

The significance of this is that lambda expressions are not dynamic methods, they are anonymous methods. If you ever look at the assembly, you will see that your lambda expressions are converted to closures with any free variables in the form of fields. The class has a method with signatures that matches yours, field variables are assigned at the dial peer.

One good way to think about this is that it means that your lambda expression is interpreted by the C # compiler at compile time, and the variables are resolved by instantiating the object from this class at runtime.

To demonstrate this, consider the following:

 var myLambda = x => x * x 

You will notice that this will not work. This is because in order to create a linked class / method, the compiler must know the type x at compile time.

All this is important because the concept of a lambda expression does not exist in the CLR at run time (in the same form as in the code). The line that looks like a lambda expression is exactly that ...

+1
source share

All Articles