sfkHooper
sfkHooper

Reputation: 79

Generate lambda expression from string

I have a need to store lambda expressions in a database and execute them dynamically. The following snippet works well as is,

float result = dataRowArray.AsEnumerable().Sum(r => r.Field<float>("ColumnA") * r.Field<float>("ColumnB"));

but I'd like to store the following part in a string...

r => r.Field<float>("ColumnA") * r.Field<float>("ColumnB")

... and inject it dynamically as in:

float result = MySession.Current.dr.AsEnumerable().Sum(storedLambdaString);

I've done a ton of Googling but I'm coming up short. Any suggestions?

Upvotes: 0

Views: 995

Answers (2)

Ashraf
Ashraf

Reputation: 36

I suggest store the query in the database and execute using LINQ like below.

using (eEntities db = new eEntities())
{
    string query = "select name,age,salary from employees"
    var employees = db.Database.SqlQuery<Employee>(query).
}

Please note: Employee is here my custom class having properties same as queried.

Upvotes: 2

Scott Stevens
Scott Stevens

Reputation: 380

Theres a nuget package that may help you "System.Linq.Dynamic". This sample code works...

 public class TestRow
{
    public Dictionary<string,float> Field { get; set; }
    public TestRow()
    {
        this.Field = new Dictionary<string, float>();
        this.Field.Add("ColumnA", 2);
        this.Field.Add("ColumnB", 3);
    }
}
class Program
{

    static void Main(string[] args)
    {
        var testRow = new TestRow();
        string expressionString = "r.Field[\"ColumnA\"] * r.Field[\"ColumnB\"]";
        var parameter = Expression.Parameter(typeof(TestRow),"r");
        var lambdaET = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { parameter }, typeof(float), expressionString);

        var result = lambdaET.Compile().DynamicInvoke(testRow);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}

Upvotes: 1

Related Questions