列表上的动态查询选择包含列表

时间:2019-04-28 21:33:10

标签: c# linq query-builder dynamicquery

我正在尝试使用c#建立动态过滤机制。

我有一个具有名称,姓氏,出生日期等属性的用户类,还有UserInformations列表,它是UserInformation对象的列表。 UserInformation对象具有属性Id,名称和值。 用户列表中的userList。

我创建了一个使用https://querybuilder.js.org/demo.html

来创建过滤器页面的UI

它会生成类似

的过滤器
{
  "condition": "AND",
  "rules": [
    {
     "id": "name",
      "field": "name",
      "type": "string",
      "input": "text",
      "operator": "equal",
      "value": "huseyin"
    },
    {
      "condition": "OR",
      "rules": [
        {
          "id": "surname",
          "field": "surname",
          "type": "string",
          "input": "text",
          "operator": "equal",
          "value": "34"
        },
        {
          "id": "ix_2_Weight",
          "field": "ix_2_Weight",
          "type": "integer",
          "input": "select",
          "operator": "equal",
          "value": 50
        }
      ]
    }
  ],
  "valid": true
}

我对具有User属性的过滤器没有任何问题。但是,我试图过滤UserInformations数组中的信息。 我正在拆分字段名称(如果其名称以ix开头)并获取用户信息的ID。但我找不到如何比较其价值。 如果它是静态linq,应该像

users.Where(u=>u.Informations.FirstOrDefault(i=>i.id==2/*id of information in filter*/)?.Value=="something"))

使用以下代码调用过滤器

 private async Task<List<User>> FilterUsers(FilterRule rule, List<UserFilterDto> users = null)
        {
            List<User> list = users ?? await GetUsersForFilter();

            var tempList = list.BuildQuery(rule).ToList();
            return tempList;

        }

动态查询部分如下。


  public static IQueryable<User> BuildQuery(this IQueryable<User> queryable, FilterRule filterRule, out string parsedQuery, bool useIndexedProperty = false, string indexedPropertyName = null)
        {
            if (filterRule == null)
            {
                parsedQuery = "";
                return queryable;
            }

            var pe = Expression.Parameter(typeof(UserDetailedDto), "item");

            var expressionTree = BuildExpressionTree(pe, filterRule, useIndexedProperty, indexedPropertyName);
            if (expressionTree == null)
            {
                parsedQuery = "";
                return queryable;
            }

            parsedQuery = expressionTree.ToString();

            var whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new[] { queryable.ElementType },
                queryable.Expression,
                Expression.Lambda<Func<UserDetailedDto, bool>>(expressionTree, pe));

            var filteredResults = queryable.Provider.CreateQuery<UserDetailedDto>(whereCallExpression);

            return filteredResults;

        }


public static IQueryable<User> BuildQuery(this IQueryable<User> queryable, FilterRule filterRule, out string parsedQuery, bool useIndexedProperty = false, string indexedPropertyName = null)
        {
            if (filterRule == null)
            {
                parsedQuery = "";
                return queryable;
            }

            var pe = Expression.Parameter(typeof(UserDetailedDto), "item");

            var expressionTree = BuildExpressionTree(pe, filterRule, useIndexedProperty, indexedPropertyName);
            if (expressionTree == null)
            {
                parsedQuery = "";
                return queryable;
            }

            parsedQuery = expressionTree.ToString();

            var whereCallExpression = Expression.Call(
                typeof(Queryable),
                "Where",
                new[] { queryable.ElementType },
                queryable.Expression,
                Expression.Lambda<Func<UserDetailedDto, bool>>(expressionTree, pe));

            var filteredResults = queryable.Provider.CreateQuery<UserDetailedDto>(whereCallExpression);

            return filteredResults;

        }

        private static Expression BuildExpressionTree(ParameterExpression pe, FilterRule rule, bool useIndexedProperty = false, string indexedPropertyName = null)
        {

            if (rule.Rules != null && rule.Rules.Any())
            {
                var expressions =
                    rule.Rules.Select(childRule => BuildExpressionTree(pe, childRule, useIndexedProperty, indexedPropertyName))
                        .Where(expression => expression != null)
                        .ToList();

                var expressionTree = expressions.First();

                var counter = 1;
                while (counter < expressions.Count)
                {
                    expressionTree = rule.Condition.ToLower() == "or"
                        ? Expression.Or(expressionTree, expressions[counter])
                        : Expression.And(expressionTree, expressions[counter]);
                    counter++;
                }

                return expressionTree;
            }
            if (rule.Field != null)
            {
                Type type;

                switch (rule.Type)
                {
                    case "integer":
                        type = typeof(int);
                        break;
                    case "long":
                        type = typeof(long);
                        break;
                    case "double":
                        type = typeof(double);
                        break;
                    case "string":
                        type = typeof(string);
                        break;
                    case "date":
                    case "datetime":
                        type = typeof(DateTime);
                        break;
                    case "boolean":
                        type = typeof(bool);
                        break;
                    default:
                        throw new Exception($"Unexpected data type {rule.Type}");
                }

                Expression propertyExp = null;

                if (rule.Field.StartsWith("ix"))
                {
                    long informationId =long.Parse(rule.Field.Split("_")[1]);

                  ????
????

                } else if (useIndexedProperty)
                {
                    propertyExp = Expression.Property(pe, indexedPropertyName, Expression.Constant(rule.Field));
                }
                else
                {
                    propertyExp = Expression.Property(pe, rule.Field);
                }

                Expression expression;

                if (propertyExp.Type.Name.Contains("ICollection") || propertyExp.Type.Name.Contains("List"))
                {
                    // Rule Field is a Collection
                    expression = BuildCollectionExpression(pe, rule);
                }
                else
                {

                    switch (rule.Operator.ToLower())
                    {
                        case "in":
                            expression = In(type, rule.Value, propertyExp);
                            break;
                        case "not_in":
                            expression = NotIn(type, rule.Value, propertyExp);
                            break;
                        case "equal":
                            expression = Equals(type, rule.Value, propertyExp);
                            break;
                        case "not_equal":
                            expression = NotEquals(type, rule.Value, propertyExp);
                            break;
                        case "between":
                            expression = Between(type, rule.Value, propertyExp);
                            break;
                        case "not_between":
                            expression = NotBetween(type, rule.Value, propertyExp);
                            break;
                        case "less":
                            expression = LessThan(type, rule.Value, propertyExp);
                            break;
                        case "less_or_equal":
                            expression = LessThanOrEqual(type, rule.Value, propertyExp);
                            break;
                        case "greater":
                            expression = GreaterThan(type, rule.Value, propertyExp);
                            break;
                        case "greater_or_equal":
                            expression = GreaterThanOrEqual(type, rule.Value, propertyExp);
                            break;
                        case "begins_with":
                            expression = BeginsWith(type, rule.Value, propertyExp);
                            break;
                        case "not_begins_with":
                            expression = NotBeginsWith(type, rule.Value, propertyExp);
                            break;
                        case "contains":
                            expression = Contains(type, rule.Value, propertyExp);
                            break;
                        case "not_contains":
                            expression = NotContains(type, rule.Value, propertyExp);
                            break;
                        case "ends_with":
                            expression = EndsWith(type, rule.Value, propertyExp);
                            break;
                        case "not_ends_with":
                            expression = NotEndsWith(type, rule.Value, propertyExp);
                            break;
                        case "is_empty":
                            expression = IsEmpty(propertyExp);
                            break;
                        case "is_not_empty":
                            expression = IsNotEmpty(propertyExp);
                            break;
                        case "is_null":
                            expression = IsNull(propertyExp);
                            break;
                        case "is_not_null":
                            expression = IsNotNull(propertyExp);
                            break;
                        default:
                            throw new Exception($"Unknown expression operator: {rule.Operator}");
                    }

                }
                return expression;


            }
            return null;

        }

1 个答案:

答案 0 :(得分:2)

  

如果它是静态LINQ,应该就像

u => u.Informations.FirstOrDefault(i => i.id == 2)?.Value == "something"))

运算符?.在表达式树中不受支持,因此最好改成这样的东西:

u => u.Informations.Any(i => i.id == 2 && i.Value == "something"))

为此,请使用另一种方法提取原始表达式构建:

private static Expression BuildCondition(FilterRule rule, Expression propertyExp)
{
    Type type;

    switch (rule.Type)
    {
        case "integer":
            type = typeof(int);
            break;
        case "long":
            type = typeof(long);
            break;
        case "double":
            type = typeof(double);
            break;
        case "string":
            type = typeof(string);
            break;
        case "date":
        case "datetime":
            type = typeof(DateTime);
            break;
        case "boolean":
            type = typeof(bool);
            break;
        default:
            throw new Exception($"Unexpected data type {rule.Type}");
    }

    Expression expression;

    switch (rule.Operator.ToLower())
    {
        case "in":
            expression = In(type, rule.Value, propertyExp);
            break;
        case "not_in":
            expression = NotIn(type, rule.Value, propertyExp);
            break;
        case "equal":
            expression = Equals(type, rule.Value, propertyExp);
            break;
        case "not_equal":
            expression = NotEquals(type, rule.Value, propertyExp);
            break;
        case "between":
            expression = Between(type, rule.Value, propertyExp);
            break;
        case "not_between":
            expression = NotBetween(type, rule.Value, propertyExp);
            break;
        case "less":
            expression = LessThan(type, rule.Value, propertyExp);
            break;
        case "less_or_equal":
            expression = LessThanOrEqual(type, rule.Value, propertyExp);
            break;
        case "greater":
            expression = GreaterThan(type, rule.Value, propertyExp);
            break;
        case "greater_or_equal":
            expression = GreaterThanOrEqual(type, rule.Value, propertyExp);
            break;
        case "begins_with":
            expression = BeginsWith(type, rule.Value, propertyExp);
            break;
        case "not_begins_with":
            expression = NotBeginsWith(type, rule.Value, propertyExp);
            break;
        case "contains":
            expression = Contains(type, rule.Value, propertyExp);
            break;
        case "not_contains":
            expression = NotContains(type, rule.Value, propertyExp);
            break;
        case "ends_with":
            expression = EndsWith(type, rule.Value, propertyExp);
            break;
        case "not_ends_with":
            expression = NotEndsWith(type, rule.Value, propertyExp);
            break;
        case "is_empty":
            expression = IsEmpty(propertyExp);
            break;
        case "is_not_empty":
            expression = IsNotEmpty(propertyExp);
            break;
        case "is_null":
            expression = IsNull(propertyExp);
            break;
        case "is_not_null":
            expression = IsNotNull(propertyExp);
            break;
        default:
            throw new Exception($"Unknown expression operator: {rule.Operator}");
    }

    return expression;
}

在当前分支内部将其用于直接成员,并将以下内容用于“索引”分支:

if (rule.Field.StartsWith("ix_"))
{
    var tokens = rule.Field.Split("_");
    var infoParameter = Expression.Parameter(typeof(UserInformation), "i");
    var infoCondition = Expression.AndAlso(
        Expression.Equal(
            Expression.Property(infoParameter, nameof(UserInformation.Id)),
            Expression.Constant(long.Parse(tokens[1]))),
        BuildCondition(rule, Expression.Property(infoParameter, tokens[2])));
    return Expression.Call(
        typeof(Enumerable), nameof(Enumerable.Any), new[] { infoParameter.Type },
        Expression.Property(pe, nameof(User.Informations)),
        Expression.Lambda(infoCondition, infoParameter));
}

请注意,C#逻辑&&||运算符由Expression.AndAlsoExpression.OrElse表示。