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
- Dictionary<string, string> dictionary = new Dictionary<string, string>();
- dictionary.Add(“Name”, “MyName”);
- DataTable dataTable = new DataTable(“Employee”);
- dataTable.Columns.Add(“Id”, typeof(Int64));
- dataTable.Columns.Add(“Name”, typeof(string));
- dataTable.Columns.Add(“Designation”, typeof(string));
- DataRow dr = dataTable.NewRow();
- dr[“Id”] = 1111;
- dr[“Name”] = “MyName”;
- dr[“Designation”] = “Accountant”;
- dataTable.Rows.Add(dr);
- DataRow dr2 = dataTable.NewRow();
- dr2[“Id”] = 1112;
- dr2[“Name”] = “YourName”;
- dr2[“Designation”] = “Receptionist”;
- dataTable.Rows.Add(dr2);
- var results = (from table in dataTable.AsEnumerable()
- join dt in dataTable.AsEnumerable() on table.Field<Int64>(“Id”) equals 1111
- select new { table = table, dictionary = dictionary }).AsQueryable();
- var ListSourceObjects = results.ToList();
- Dictionary<string, object> symbols = new Dictionary<string, object>();
- symbols.Add(“employeeTable”, ListSourceObjects[0].table);
- symbols.Add(“employeeList”, ListSourceObjects[0].dictionary);
- string strExpression = @”employeeTable[“”Name””].ToString() == employeeList[“”Name””]”;
- var body = System.Linq.Dynamic.DynamicExpression.Parse(typeof(bool), strExpression, symbols);
- LambdaExpression e = Expression.Lambda(body);
- 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.