开发者

Linq expression replace parameter type

I have a predicate, that was made from lambda expression after all extension methods were served. For example:

(new List<string>).Where(i => i.Contains("some")).Where(i => i.Contains("second_some")开发者_运维技巧);

"List<>" is only example, there could be my custom data context or object collection. So, I have an "Expression<...>", and it's base type "Expression".

The question is, is there are any code, which could walk the tree of expression, and replace parameter type (in our sample it is "string") with another one specified?

I have already found how to replace parameter type, but it has a conflict when the method somewhere from "Where" extension method has a signature with old parameter type.

Maybe someone has met solution? Thanks.


An expression is an immutable type. To replace parameters (and their type) you sould create a new expression using the body of the original expression, passing the parameters you want to use.

            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")}

It is not really a good practice to build expressions using linq (method) syntax and then walk the tree to build a new expression. If i were you i would try to build the expression using Expression.Call & Expression.Lambda & Expression.Paremeter... syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜