簡體   English   中英

Linq表達式替換參數類型

[英]Linq expression replace parameter type

我有一個謂詞,它是在使用所有擴展方法后由lambda表達式制成的。 例如:

(new List<string>).Where(i => i.Contains("some")).Where(i => i.Contains("second_some"));

“ List <>”僅是示例,可能有我的自定義數據上下文或對象集合。 因此,我有一個“ Expression <...>”,它的基本類型是“ Expression”。

問題是,是否有任何代碼可以遍歷表達式樹,並用另一個指定的代碼替換參數類型(在我們的示例中為“字符串”)?

我已經找到了如何替換參數類型,但是當“ Where”擴展方法中某處的方法具有帶有舊參數類型的簽名時,就會發生沖突。

也許有人遇到了解決方案? 謝謝。

表達式是不可變的類型。 要替換參數(及其類型),您可以使用原始表達式的主體創建一個新表達式,並傳遞要使用的參數。

            var resultingIQueryable = ( new List<string> () ).AsQueryable<string>().Where (i => i.Contains ("some")).Where (i => i.Contains ("second_some"));

            // the Queryable.Where is a MethodCallExpression
            var expressionOriginal = resultingIQueryable.Expression as MethodCallExpression;
            // there are multiple where calls, this makes it all a little bit more confusing.
            // The linq tree is built 'backwards'
            // the first parameter of the expression is a MethodCallExpression:
            // {System.Collections.Generic.List`1[System.String].Where(i => i.Contains("some"))}
            // the second parameter:
            // {i => i.Contains("second_some")}
            //
            // disecting the first parameter you will again find 2 parameters:
            // {System.Collections.Generic.List`1[System.String]} 
            // {i => i.Contains("some")}

使用linq(方法)語法構建表達式,然后遍歷樹來構建新表達式並不是一個好習慣。 如果我是我,我將嘗試使用Expression.Call和Expression.Lambda和Expression.Paremeter ...語法來構建表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM