整数包含linq c#,但使用表达式

时间:2018-11-16 05:09:14

标签: c# linq linq-expressions

我想使用linq表达式为我的存储库创建一个动态过滤器,我还有其他过滤器,但是我不知道如何使用表达式创建下一个:(条件取自here

var result = _studentRepotory.GetAll().Where(s => 
SqlFunctions.StringConvert((double)s.Id).Contains("91")).ToList();

我有一个方法可以接收属性的值,propertyName和过滤器运算符类型(枚举):

public static class Helper {
    public static Expression<Func<T, bool>> GetExpression<T>(object value, string propertyName, FilterOperatorType FilterType)
    {
        var parameter = Expression.Parameter(typeof(T));
        var property = ExpressionUtils.GetPropertyChild(parameter, propertyName);
        var constValue = Expression.Constant(value);

        BinaryExpression expresion = null;
        switch (FilterType)
        {
            case FilterOperatorType.Equal:
                expresion = Expression.Equal(property, constValue);
                break;
            case FilterOperatorType.Greater:
                expresion = Expression.GreaterThan(property, constValue);
                break;
            case FilterOperatorType.Less:
                expresion = Expression.LessThan(property, constValue);
                break;
            case FilterOperatorType.GreaterOrEqual:
                expresion = Expression.GreaterThanOrEqual(property, constValue);
                break;
            case FilterOperatorType.LessOrEqual:
                expresion = Expression.LessThanOrEqual(property, constValue);
                break;
        }

        var lambda = Expression.Lambda<Func<T, bool>>(expresion, parameter);
        return lambda;
    }
}

因此,我想添加一个新的运算符类型包含,该运算符将评估整数是否包含一些数字,在我的第一段代码中,但是我想使用linq表达式来实现使用泛型。

最后我将拥有:

Expression<Func<Student, bool>> where = Helper.GetExpression<Student>("91", "Id",  FilterOperatorType.Contains);
var result = _studentRepotory.GetAll().Where(where).ToList();

当ID包含数字91时,查询应返回所有学生。

请帮助我,并告诉我您是否理解。

1 个答案:

答案 0 :(得分:4)

我现在是2:00,并且仍在进行此操作,那时大脑工作得更好,呵呵,这是创建表达式的解决方案:

object value = "91";

var parameter = Expression.Parameter(typeof(Student));
var property = ExpressionUtils.GetPropertyChild(parameter, "Id");
var constValue = Expression.Constant(value);

var expressionConvert = Expression.Convert(property, typeof(double?));

var methodStringConvert = typeof(SqlFunctions).GetMethod("StringConvert",
                    BindingFlags.Public | BindingFlags.Static, null,
                    CallingConventions.Any,
                    new Type[] { typeof(double?) },
                    null);

var methodContains = typeof(string).GetMethod("Contains", 
            BindingFlags.Public | BindingFlags.Instance,
            null, CallingConventions.Any,
            new Type[] { typeof(String) }, null);

var expresionStringConvert = Expression.Call(methodStringConvert, expressionConvert);
var expresionContains = Expression.Call(expresionStringConvert, methodContains, constValue);
var lambdaContains = Expression.Lambda<Func<Student, bool>>(expresionContains, parameter);

现在您可以在StudentRepository的Where方法中使用lambdaContains