#TECH

Dynamic Expression Evaluation using LINQ and Lambda Expressions

There are times when we need to evaluate an expression at run time. We can either write a custom parser or use .NET Compilers which will compile the code at runtime. But these compilers might take a significant amount of time to compile the code. A parser can parse the dynamic expression and further generate the result of the expression.

Consider we have a Dictionary and a DataTable. I have an expression that requires a KeyPairValue to be evaluated against a DataRow object. System.Linq.Dynamic and System.Linq.Expressions are the assemblies you all need.

Code Snippet
  1. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  2. dictionary.Add(“Name”, “MyName”);
  3. DataTable dataTable = new DataTable(“Employee”);
  4. dataTable.Columns.Add(“Id”, typeof(Int64));
  5. dataTable.Columns.Add(“Name”, typeof(string));
  6. dataTable.Columns.Add(“Designation”, typeof(string));
  7. DataRow dr = dataTable.NewRow();
  8. dr[“Id”] = 1111;
  9. dr[“Name”] = “MyName”;
  10. dr[“Designation”] = “Accountant”;
  11. dataTable.Rows.Add(dr);
  12. DataRow dr2 = dataTable.NewRow();
  13. dr2[“Id”] = 1112;
  14. dr2[“Name”] = “YourName”;
  15. dr2[“Designation”] = “Receptionist”;
  16. dataTable.Rows.Add(dr2);
  17. var results = (from table in dataTable.AsEnumerable()
  18.                join dt in dataTable.AsEnumerable() on table.Field<Int64>(“Id”) equals 1111
  19.                select new { table = table, dictionary = dictionary }).AsQueryable();
  20. var ListSourceObjects = results.ToList();
  21. Dictionary<string, object> symbols = new Dictionary<string, object>();
  22. symbols.Add(“employeeTable”, ListSourceObjects[0].table);
  23. symbols.Add(“employeeList”, ListSourceObjects[0].dictionary);
  24. string strExpression = @”employeeTable[“”Name””].ToString() == employeeList[“”Name””]”;
  25. var body = System.Linq.Dynamic.DynamicExpression.Parse(typeof(bool), strExpression, symbols);
  26. LambdaExpression e = Expression.Lambda(body);
  27. var result = e.Compile().DynamicInvoke();

 

You can provide any entity, DataSet, DataTable for the result set and just query over the objects. You can use this result set to fetch the values.

You might also like