开发者

In C#, how can i add a null check into dynamic express code

i am leveraging this project to use jqgrid to filter and sort collections. The one issue i see if that, when looping through the collection and checking the property of a string field is null, this code below will blow up. i want to tweak the code below so it creates a lambda that not only does a "ToString()" and "Contains" but also support if a property is null (and treats it as string.empty)

I basically have 2 inputs into this function below:

  1. FieldName
  2. Data Value

and the code below is dynamically b开发者_开发知识库uilding up an expression to loop through a collection and check "Contains" against the property that maps onto the FieldName being passed in.

i have code that looks like this:

        ParameterExpression parameter = Expression.Parameter(query.ElementType, "p");

        MemberExpression memberAccess = null;
        MethodCallExpression memberAccessToString = null;
        foreach (var property in column.Split('.'))
        {
            memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property);
            memberAccessToString = MemberExpression.Call(memberAccess, "ToString", new Type[] {}, new Expression[] {});
        }

        Expression condition = null;
        LambdaExpression lambda = null;
            case WhereOperation.Contains:
                condition = Expression.Call(memberAccessToString,
                    typeof(string).GetMethod("Contains"),
                    Expression.Constant(value));
                lambda = Expression.Lambda(condition, parameter);

        MethodCallExpression result = Expression.Call(
               typeof(Queryable), "Where",
               new[] { query.ElementType },
               query.Expression,
               lambda);

        return query.Provider.CreateQuery<T>(result);


Have you checked Expression.Coalesce you could apply it to memberAccess before calling ToString()

memberAccess = MemberExpression.Property(memberAccess ?? (parameter as Expression), property);
memberAccessToString = MemberExpression.Call(Expression.Coalesce(memberAccess,Expression.Constant(string.Empty)), "ToString", new Type new Type[] {}, new Expression[] {});

Didn't test it but may lead to the solution

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜