记录Linq中lambda动态表达式的使用方式
项目中有的时候我们会用到动态表达式的方式去查询数据,这里简单记录下个人的使用方式,方便使用↓
1 //构建参数表达式 2 ParameterExpression parameter = Expression.Parameter(typeof(SimpleResult)); 3 Expression conditionValue = Expression.Equal(Expression.Property(parameter, groupFileName), Expression.Constant(value, typeof(Object))); 4 var lambdaValue = Expression.Lambda<Func<SimpleResult, bool>>( 5 conditionValue, 6 parameter); 7 var groupCount = resultData.AsQueryable().Count(lambdaValue); 8 var item = new GroupModel { GroupName = groupFileName, GroupValue = value?.ToString(), GroupCount = groupCount }; 9 listObj.Add(item); 10 11 12 13 /* 14 15 1、创建表达式 16 2、创建表达式参数 17 3、查询 18 19 */ 20 21 // 表达式传过去的参数 22 // ParameterExpression parameter1 = Expression.Parameter(typeof(SimpleResult), "o"); 23 // 使用的字段 24 //MemberExpression member1 = Expression.PropertyOrField(parameter1, groupFileName); 25 // 要比较的值 26 //ConstantExpression constant1 = Expression.Constant(value, typeof(Object)); 27 // query 28 //var query = Expression.Equal(member1, constant1);//Equal等于;GreaterThanOrEqual大于;LessThanOrEqual小于 29 30 // var lambda = Expression.Lambda<Func<SimpleResult, bool>>(query, parameter1); 31 32 // var groupCount2 = resultData.AsQueryable().Count(lambda);
还有另外一种动态表达式的使用方式,通过安装DynamicExpresso.CoreNuget包
参考地址:https://github.com/davideicardi/DynamicExpresso
1 ==============================(Install - Package DynamicExpresso.Core)====================================== 2 3 var whereExpression = $"m.{queryField}==\"{queryValue}\""; 4 5 string whereExpression = "customer.Age > 18 && customer.Gender == 'F'"; 6 7 var interpreter = new Interpreter(); 8 Func<Customer, bool> dynamicWhere = interpreter.ParseAsDelegate<Func<Customer, bool>>(whereExpression, "customer"); 9 10 Assert.AreEqual(1, customers.Where(dynamicWhere).Count()); 11 12 ===================================================================================================== 13 string whereExpression = "customer.Age > 18 && customer.Gender == 'F'"; 14 15 var interpreter = new Interpreter(); 16 Expression<Func<Customer, bool>> expression = interpreter.ParseAsExpression<Func<Customer, bool>>(whereExpression, "customer"); 17 18 Assert.AreEqual(1, customers.Where(expression).Count());
学习本无底,前进莫徬徨。 好好学习,天天向上。