我正在嘗試寫一些將允許自定義表達式存儲在字符串中以評估各種數據的東西。在幾次失敗的嘗試之後,我找到了一些成功的東西,但它不適合這種意圖。使用LINQ來根據數據表從字符串計算表達式
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Age", typeof(int)));
dt.Rows.Add(new object[] { "John", 32 });
var test = dt.AsEnumerable().AsQueryable();
// An example of an expression to test
string expression = "Age = 32";
// Failed Attempts
//var result1 = test.Where(expression); // Error received: {"No property or field 'Age' exists in type 'DataRow'"}
//var result2 = test.Where("it.Field<object>(\"Age\") == 32"); // Error received: {"No property or field 'Field' exists in type 'DataRow'"}
//var result3 = test.Where("[email protected]", 32); // Error received: {"No property or field 'Age' exists in type 'DataRow'"}
//var result4 = test.Where("it[\"Age\"] == 127"); // Error received: {"Operator '==' incompatible with operand types 'Object' and 'Int32'"}
//var result5 = test.Where("it[\"Age\"] = 127"); // Error received: {"Operator '=' incompatible with operand types 'Object' and 'Int32'"}
//var result6 = test.Where("it[\"Age\"] as Age = 127"); // Error received: {"Expression of type 'Boolean' expected"}
// Successful but at this point its not really a dynamic linq expression
var result = test.Where(it => it.Field<int>("Age") == 32);
我該如何做到這一點?所有的道路似乎都回到這篇文章:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx但是我沒有看到我正在使用強類型數據時所要做的事情的答案。
謝謝!
這不是'linq',而是[ 'DataTable.Select()'](http://msdn.microsoft.com/en-us/library/system.data.datatable.select.aspx)方法會有幫助嗎? – DaveParsons
我從來沒有嘗試過使用Dynamic Linq和DataTable。我想知道你是否會考慮不使用DataTable的選項? –
這將工作:dt.Select(「年齡= 32」);這也會起作用:dt.AsEnumerable()。where(a => a [「Name」]。Equals(「John」)); – Arie