2015-12-06 59 views
0

根據要求,我想使用C#創建動態lambda表達式。數組屬性過濾器的動態lambda表達式

比如我想生成像

Employee. Address[1].City 

我怎樣才能做到這一點的動態查詢?請注意,該酒店是一個充滿活力的酒店。

我已經試過這個代碼

var item = Expression.Parameter(typeof(Employee), "item"); 

Expression prop = Expression.Property(item, "Address", new Expression[] { Expression.Constant[1] }); 
prop = Expression.Property(prop, "City"); 

var propValue = Expression.Constant(constraintItem.State); 
var expression = Expression.Equal(prop, propValue); 
var lambda = Expression.Lambda<Func<Line, bool>>(expression, item); 

但沒有奏效。

任何幫助,將不勝感激。

謝謝。

+0

是'Address'一個索引?如果它是一個數組,使用'Expression.ArrayIndex',如果它只是一個帶有索引器的列表,使用未索引的'Expression.Property'檢索列表,然後在其Items屬性上應用索引屬性檢索表達式。 –

回答

2

你的「動態查詢」表達(這是不是一個真正的查詢,這是一個簡單的MemberExpression)可以如下產生:

ParameterExpression param = Expression.Parameter(typeof(Employee), "item"); 
MemberExpression address = Expression.Property(param, "Address"); 
BinaryExpression indexedAddress = Expression.ArrayIndex(address, Expression.Constant(1)); 
MemberExpression city = Expression.Property(indexedAddress, "City"); // Assuming "City" is a string. 

// This will give us: item => item.Address[1].City 
Expression<Func<Employee, string>> memberAccessLambda = Expression.Lambda<Func<Employee, string>>(city, param); 

如果你想要一個實際謂詞的一部分使用你的查詢,你只包住MemberExpression與相關比較表達式,即

BinaryExpression eq = Expression.Equal(city, Expression.Constant("New York")); 

// This will give us: item => item.Address[1].City == "New York" 
Expression<Func<Employee, bool>> predicateLambda = Expression.Lambda<Func<Employee, bool>>(eq, param); 

在代碼方面:不知道你爲什麼肌酸g當代表輸入明顯預期爲Employee時,代表類型爲Func<Line, bool>的lambda。參數類型必須始終與委託簽名匹配。

編輯

非數組索引訪問例如:

ParameterExpression param = Expression.Parameter(typeof(Employee), "item"); 
MemberExpression address = Expression.Property(param, "Address"); 

IndexExpression indexedAddress = Expression.MakeIndex(
    address, 
    indexer: typeof(List<string>).GetProperty("Item", returnType: typeof(string), types: new[] { typeof(int) }), 
    arguments: new[] { Expression.Constant(1) } 
); 

// Produces item => item.Address[1]. 
Expression<Func<Employee, string>> lambda = Expression.Lambda<Func<Employee, string>>(indexedAddress, param); 

// Predicate (item => item.Address[1] == "Place"): 
BinaryExpression eq = Expression.Equal(indexedAddress, Expression.Constant("Place")); 
Expression<Func<Employee, bool>> predicateLambda = Expression.Lambda<Func<Employee, bool>>(eq, param); 
+0

感謝您的回覆。需求略有變化。地址是Employee類中的列表屬性。 – Ranish

+0

我收到以下錯誤「在System.Core.dll中發生類型'System.ArgumentException'的未處理異常」 – Ranish

+0

需求是爲x.Address [1] =='Place'生成查詢。謝謝!! – Ranish