schangxiang@126.com
2024-06-11 3ac98ce77d7b2b610351ee98f232e316abac9d3b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System.Linq.Expressions;
using System.Reflection;
 
namespace iWare.Wms.Core
{
    /// <summary>
    /// 动态生成查询表达式
    /// </summary>
    public static class LambdaExpressionBuilder
    {
        private static Expression GetExpression(ParameterExpression parameter, Condition condition)
        {
            var propertyParam = Expression.Property(parameter, condition.Field);
 
            var propertyInfo = propertyParam.Member as PropertyInfo;
            if (propertyInfo == null)
                throw new MissingMemberException(nameof(Condition), condition.Field);
 
            //Support Nullable<>
            var realPropertyType = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
            if (propertyInfo.PropertyType.IsGenericType &&
                propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                propertyParam = Expression.Property(propertyParam, "Value");
 
            //Support IEnumerable && IEnumerable<T>
            if (condition.Op != QueryTypeEnum.StdIn && condition.Op != QueryTypeEnum.StdNotIn)
            {
                condition.Value = Convert.ChangeType(condition.Value, realPropertyType);
            }
            else
            {
                var typeOfValue = condition.Value.GetType();
                var typeOfList = typeof(IEnumerable<>).MakeGenericType(realPropertyType);
                if (typeOfValue.IsGenericType && typeOfList.IsAssignableFrom(typeOfValue))
                    condition.Value = typeof(Enumerable)
                        .GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static)
                        ?.MakeGenericMethod(realPropertyType)
                        .Invoke(null, new[] { condition.Value });
            }
 
            var constantParam = Expression.Constant(condition.Value);
            switch (condition.Op)
            {
                case QueryTypeEnum.Equals:
                    return Expression.Equal(propertyParam, constantParam);
 
                case QueryTypeEnum.NotEquals:
                    return Expression.NotEqual(propertyParam, constantParam);
 
                case QueryTypeEnum.Contains:
                    return Expression.Call(propertyParam, "Contains", null, constantParam);
 
                case QueryTypeEnum.NotContains:
                    return Expression.Not(Expression.Call(propertyParam, "Contains", null, constantParam));
 
                case QueryTypeEnum.StartsWith:
                    return Expression.Call(propertyParam, "StartsWith", null, constantParam);
 
                case QueryTypeEnum.EndsWith:
                    return Expression.Call(propertyParam, "EndsWith", null, constantParam);
 
                case QueryTypeEnum.GreaterThan:
                    return Expression.GreaterThan(propertyParam, constantParam);
 
                case QueryTypeEnum.GreaterThanOrEquals:
                    return Expression.GreaterThanOrEqual(propertyParam, constantParam);
 
                case QueryTypeEnum.LessThan:
                    return Expression.LessThan(propertyParam, constantParam);
 
                case QueryTypeEnum.LessThanOrEquals:
                    return Expression.LessThanOrEqual(propertyParam, constantParam);
 
                case QueryTypeEnum.StdIn:
                    return Expression.Call(typeof(Enumerable), "Contains", new[] { realPropertyType }, constantParam, propertyParam);
 
                case QueryTypeEnum.StdNotIn:
                    return Expression.Not(Expression.Call(typeof(Enumerable), "Contains", new[] { realPropertyType }, constantParam, propertyParam));
 
                default:
                    break;
            }
 
            return null;
        }
 
        private static Expression GetGroupExpression(ParameterExpression parameter, List<Condition> orConditions)
        {
            if (orConditions.Count == 0)
                return null;
 
            var exps = orConditions.Select(c => GetExpression(parameter, c)).ToList();
            return exps.Aggregate<Expression, Expression>(null, (left, right) =>
                left == null ? right : Expression.OrElse(left, right));
        }
 
        public static Expression<Func<T, bool>> BuildLambda<T>(IEnumerable<Condition> conditions)
        {
            if (conditions == null || !conditions.Any())
                return x => true;
 
            var parameter = Expression.Parameter(typeof(T), "x");
 
            //简单条件
            var simpleExps = conditions
                .ToList()
                .FindAll(c => string.IsNullOrEmpty(c.OrGroup))
                .Select(c => GetExpression(parameter, c))
                .ToList();
 
            //复杂条件
            var complexExps = conditions
                .ToList()
                .FindAll(c => !string.IsNullOrEmpty(c.OrGroup))
                .GroupBy(x => x.OrGroup)
                .Select(g => GetGroupExpression(parameter, g.ToList()))
                .ToList();
 
            var exp = simpleExps.Concat(complexExps).Aggregate<Expression, Expression>(null, (left, right) =>
                left == null ? right : Expression.AndAlso(left, right));
            return Expression.Lambda<Func<T, bool>>(exp, parameter);
        }
 
        public static Expression<Func<T, bool>> BuildAndAlsoLambda<T>(IEnumerable<Condition> conditions)
        {
            if (conditions == null || !conditions.Any())
                return x => true;
 
            var parameter = Expression.Parameter(typeof(T), "x");
            var simpleExps = conditions
                .ToList()
                .Select(c => GetExpression(parameter, c))
                .ToList();
 
            var exp = simpleExps.Aggregate<Expression, Expression>(null, (left, right) =>
                left == null ? right : Expression.AndAlso(left, right));
            return Expression.Lambda<Func<T, bool>>(exp, parameter);
        }
 
        public static Expression<Func<T, bool>> BuildOrElseLambda<T>(IEnumerable<Condition> conditions)
        {
            if (conditions == null || !conditions.Any())
                return x => true;
 
            var parameter = Expression.Parameter(typeof(T), "x");
            var simpleExps = conditions
                .ToList()
                .Select(c => GetExpression(parameter, c))
                .ToList();
 
            var exp = simpleExps.Aggregate<Expression, Expression>(null, (left, right) =>
                left == null ? right : Expression.OrElse(left, right));
            return Expression.Lambda<Func<T, bool>>(exp, parameter);
        }
    }
 
    /// <summary>
    /// 查询条件
    /// </summary>
    [Serializable]
    public class Condition
    {
        /// <summary>
        /// 字段名
        /// </summary>
        public string Field { get; set; }
 
        /// <summary>
        /// 操作符
        /// </summary>
        public QueryTypeEnum Op { get; set; }
 
        /// <summary>
        /// 字段值
        /// </summary>
        public object Value { get; set; }
 
        /// <summary>
        /// 分组名称
        /// </summary>
        public string OrGroup { get; set; }
    }
}