LINQ Expression> equavalent of .Contains()

前端 未结 2 1985
别那么骄傲
别那么骄傲 2021-02-14 23:32

Has anybody got an idea of how to create a .Contains(string) function using Linq Expressions, or even create a predicate to accomplish this

public static Express         


        
2条回答
  •  旧时难觅i
    2021-02-15 00:28

    I use something similiar, where I add filters to a query.

    public static Expression> PropertyStartsWith(PropertyInfo property, TypeOfPropery value)
    {
         var parent = Expression.Parameter(typeof(TypeOfParent));
         MethodInfo method = typeof(string).GetMethod("StartsWith",new Type[] { typeof(TypeOfPropery) });
         var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
         return Expression.Lambda>(expressionBody, parent);
    }
    

    Usage, to apply filter against a property whose name matches Key, and using supplied value, Value.

    public static IQueryable ApplyParameters(this IQueryable query, List gridParameters)
    {
    
       // Foreach Parameter in List
       // If Filter Operation is StartsWith
        var propertyInfo = typeof(T).GetProperty(parameter.Key);
        query = query.Where(PropertyStartsWith(propertyInfo, parameter.Value));
    }
    

    And yes, this method works with contains:

            public static Expression> PropertyContains(PropertyInfo property, TypeOfPropery value)
        {
            var parent = Expression.Parameter(typeof(TypeOfParent));
            MethodInfo method = typeof(string).GetMethod("Contains", new Type[] { typeof(TypeOfPropery) });
            var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
            return Expression.Lambda>(expressionBody, parent);
        }
    

    By having those 2 examples, you can more easily understand how we can call various different methods by name.

提交回复
热议问题