Expression表达式树 案例
1,Expression.Invoke
//运用委托或Lambda表达式
System.Linq.Expressions.Expression<Func<int, int, bool>> largeSumTest =(num1, num2) => (num1 + num2) > ;
System.Linq.Expressions.InvocationExpression invocationExpression =
System.Linq.Expressions.Expression.Invoke(
largeSumTest,
System.Linq.Expressions.Expression.Constant(),
System.Linq.Expressions.Expression.Constant());
Console.WriteLine(invocationExpression.ToString());//输出:Invoke((num1, num2) => ((num1 + num2) > 1000), 539, 281)
Console.WriteLine(Expression.Lambda<Func<bool>>(invocationExpression).Compile()());//计算委托 返回false
Console.ReadKey();
案例:
//执行1+2
var a = Expression.Add(Expression.Constant(), Expression.Constant());
var lambda = Expression.Lambda<Func<int>>(a).Compile();
Console.WriteLine(lambda());
//执行Math.Sin()
var p = Expression.Parameter(typeof(double), "a");
//Sin(a)
var exp = Expression.Call(null, typeof(Math).GetMethod("Sin", BindingFlags.Public | BindingFlags.Static), p);
//a=>Sin(a)
var l = Expression.Lambda<Func<double,double>>(exp, p).Compile();
Console.WriteLine(l());
//执行i => i委托
Expression<Func<int, int>> ex1 = i => i;
var paraemter = Expression.Parameter(typeof(int), "a");
Console.WriteLine(Expression.Lambda<Func<int, int>>(Expression.Invoke(ex1, paraemter), paraemter).Compile()());
//输出:((r.Name == "张三") AndAlso Invoke(r => (r.Sex == "男"), r))
Expression<Func<Product, bool>> where = r => r.Name == "张三";
Expression<Func<Product, bool>> where2 = r => r.Sex == "男";
var invoke = Expression.Invoke(where2, where.Parameters);
Console.WriteLine(invoke);
var and = Expression.AndAlso(where.Body, invoke);
Console.WriteLine(and);
using LinqKit;
//ef查询
DbContext db = new DbContext(ConfigurationManager.ConnectionStrings["blogEntities"].ConnectionString);
Expression<Func<products, bool>> where = r => true;
Expression<Func<products, bool>> wherename = r => r.Name == "asd";
where = Expression.Lambda<Func<products, bool>>(Expression.AndAlso(where.Body, Expression.Invoke(wherename,where.Parameters)), where.Parameters);
var ps = db.Set<products>().AsNoTracking().AsExpandable().Where(where).AsQueryable().ToList();
foreach (var item in ps)
{
Console.WriteLine($"id:{item.Id} qty:{item.Qty} name:{item.Name} aa:{item.AA}");
}
//执行Lambda r => r 输出:1
Expression<Func<int, int>> exr = r => r;
var invoke = Expression.Invoke(exr, Expression.Constant());
var d = Expression.Lambda(invoke).Compile();
Console.WriteLine(d.DynamicInvoke());
一、QueryFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Reflection; namespace QueryFilterComplete
{
public class QueryFilter
{ /// <summary>
/// 查询条件过滤
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="valNames">需要过滤的字段</param>
/// <param name="vagueNames">需要模糊查询的字段</param>
/// <param name="isIgnoreZero">true:忽略0</param>
/// <returns></returns>
public static Expression<Func<T, Boolean>> Filter<T,Twhere>(Twhere t, IEnumerable<string> valNames, IEnumerable<string> vagueNames, bool isIgnoreZero = true) where T : class where Twhere:class
{
Expression<Func<T, Boolean>> e = r => true;
foreach (var item in valNames)
{
var result = GetFilterType(item, vagueNames);
if (result.Item1 == QFilterType.None) continue;
PropertyInfo property = typeof(Twhere).GetProperty(item);
var value = property.GetValue(t);
if (!Validate(property.PropertyType, value, isIgnoreZero)) continue; var rE = Expression.Parameter(typeof(T), "r");
var propertyE = Expression.Property(rE, result.Item2);
var valueE = Expression.Constant(value);
var lambda = Expression.Lambda<Func<T, Boolean>>(ComputeExpression(result.Item1, t, property, propertyE, valueE), rE);
var invoke = Expression.Invoke(lambda, e.Parameters);
e = Expression.Lambda<Func<T, Boolean>>(Expression.AndAlso(e.Body, invoke), e.Parameters);
}
return e;
}
private static bool Validate(Type t,object value, bool isIgnoreZero)
{
if (value == null) return false;
if (t.IsValueType)
{
if (t == typeof(DateTime)) return true;
if (t == typeof(bool)) return true;
if (Convert.ToDouble(value) == && isIgnoreZero) return false;
}
return true;
} //获取过滤类型
private static Tuple<QFilterType, string> GetFilterType(string valName, IEnumerable<string> vagueNames)
{
QFilterType type = QFilterType.None;
string propertyName = "";
if (string.IsNullOrEmpty(valName)) {
return Tuple.Create(type, propertyName);
}
type = QFilterType.Equal;
propertyName = valName;
if (valName.EndsWith("_ge"))
{
type = QFilterType.ge;
propertyName = valName.TrimEnd('_', 'g', 'e');
}
if (valName.EndsWith("_gt"))
{
type = QFilterType.gt;
propertyName = valName.TrimEnd('_', 'g', 't');
}
if (valName.EndsWith("_le"))
{
type = QFilterType.le;
propertyName = valName.TrimEnd('_', 'l', 'e');
}
if (valName.EndsWith("_lt"))
{
type = QFilterType.lt;
propertyName = valName.TrimEnd('_', 'l', 't');
}
if (valName.EndsWith("_ne"))
{
type = QFilterType.ne;
propertyName = valName.TrimEnd('_', 'n', 'e');
}
if (valName.EndsWith("_csv"))
{
type = QFilterType.csv;
propertyName = valName.TrimEnd('_', 'c', 's', 'v');
}
if (vagueNames!=null&&vagueNames.Contains(valName))
{
type = QFilterType.VaguesEqual;
propertyName = valName;
}
return Tuple.Create(type, propertyName);
}
private static Expression ComputeExpression<T>(QFilterType type,T t, PropertyInfo pInfo, Expression propertyE, Expression valueE)
{
if (type == QFilterType.Equal)
{
return Expression.Equal(propertyE, valueE);
}
if (type == QFilterType.VaguesEqual)
{
//Console.WriteLine(Expression.Call(typeof(Program), "VaguesEqual", null, p, value));
return Expression.Call(typeof(QueryFilter), "VaguesEqual", null, propertyE, valueE);
}
if (type == QFilterType.ge)
{
return Expression.GreaterThanOrEqual(propertyE, valueE);
}
if (type == QFilterType.gt)
{
return Expression.GreaterThan(propertyE, valueE);
}
if (type == QFilterType.le)
{
return Expression.LessThanOrEqual(propertyE, valueE);
}
if (type == QFilterType.lt)
{
return Expression.LessThan(propertyE, valueE);
}
if (type == QFilterType.ne)
{
return Expression.NotEqual(propertyE, valueE);
}
if (type == QFilterType.csv)
{
if (pInfo.PropertyType.GetGenericTypeDefinition()==typeof(IEnumerable<>) || pInfo.PropertyType.IsSubclassOf(typeof(IEnumerable<>)))
{
return Expression.Call(typeof(QueryFilter), "VaguesEqual", new Type[] { pInfo.PropertyType.GenericTypeArguments[] },Expression.Constant(pInfo.GetValue(t)), propertyE);
}
}
return null;
} private static bool VaguesEqual<T>(IEnumerable<T> t, T value)
{
return t.Contains(value);
}
//模糊匹配
private static bool VaguesEqual(string t, string value)
{
return t.Contains(value);
} }
}
下载地址v1:http://pan.baidu.com/s/1jI1I2MU
Expression表达式树 案例的更多相关文章
- 介绍一个可以将Expression表达式树解析成Transact-SQL的项目Expression2Sql
一.Expression2Sql介绍 Expression2Sql是一个可以将Expression表达式树解析成Transact-SQL的项目.简单易用,几分钟即可上手使用,因为博主在设计Expres ...
- 委托、匿名委托、Lambda 表达式、Expression表达式树之刨根问底
本篇不是对标题所述之概念的入门文章,重点在阐述它们的异同点和应用场景.各位看官,这里就不啰嗦了,直接上代码. 首先定义一个泛型委托类型,如下: public delegate T Function&l ...
- .net 系列:Expression表达式树、lambda、匿名委托 的使用
首先定义一个泛型委托类型,如下: public delegate T Function<T>(T a, T b); 实现泛型委托的主体代码,并调用: public static strin ...
- .net 系列:Expression表达式树、lambda、匿名委托 的使用【转】
https://www.cnblogs.com/nicholashjh/p/7928205.html 首先定义一个泛型委托类型,如下: public delegate T Function<T& ...
- Expression表达式树(C#)
Lambda表达式: 1.下面举例通过Lambda表达式创建了一个用于验证Name的Func委托. //通过Lambda表达式创建一个对象的Name属性验证委托 Func<SearchInfo, ...
- .NET技术-6.0. Expression 表达式树 生成 Lambda
.NET技术-6.0. Expression 表达式树 生成 Lambda public static event Func<Student, bool> myevent; public ...
- Expression表达式树
表达式树表示树状数据结构的代码,树状结构中的每个节点都是一个表达式,例如一个方法调用或类似 x < y 的二元运算 1.利用 Lambda 表达式创建表达式树 Expression<Fun ...
- 关于Expression表达式树的拼接
最近在做项目中遇到一个问题,需求是这样的: 我要对已经存在的用户进行检索,可以根据用户的id 或者用户名其中的一部分字符来检索出来,这样就出现了三种情况 只有id,只有用户名中一部字符,或者全部都有. ...
- Expression 表达式树学习整理
整理了一下表达式树的一些东西,入门足够了 先从ConstantExpression 开始一步一步的来吧 它表示具有常量值的表达式 我们选建一个控制台应用程序 ConstantExpression _ ...
随机推荐
- web打印难题—背景不打印的简单不完美解决方案
web打印在一些开发中是比较常见的需求,最简单的办法是使用css print进行控制:对于一些建议可以参考http://slodive.com/web-development/css-print-pa ...
- ubuntu 开机自动挂在windows下的分区
最近装了Ubuntu14.04 + windows7 的双系统,启动Ubuntu的时候,不会自动挂载win7的分区,只有我点击相应的硬盘符号时才会挂载/media下面.本着折腾到底的原则,在网上搜了搜 ...
- solr后台界面介绍——(十一)
1.加一个collection的方法 复制solr-home下的collection1,修改名字为collection2.并且修改collection2文件夹中配置文件core.properties中 ...
- Exif xss
这种XSS出现的状况会特别少. Exif是啥??? 可交换图像文件格式(英语:Exchangeable image file format,官方简称Exif),是专门为数码相机的照片设定的,可以记录数 ...
- Oracle 11G R2 RAC中的scan ip 的用途和基本原理【转】
Oracle 11G R2 RAC增加了scan ip功能,在11.2之前,client链接数据库的时候要用vip,假如你的cluster有4个节点,那么客户端的tnsnames.ora中就对应有四个 ...
- python 元组分组并排序
# -*- coding: utf-8 -*- # @Time : 2018/8/31 14:32 # @Author : cxa # @File : glomtest.py # @Software: ...
- 使用Cache缓存
存放位置:服务器内存,用于频繁访问且不轻易更改的内容缓存. string CacheKey = "CT1"; //检索指定项, object objModel = Cache.Ge ...
- clog,cout,cerr 输出机制
clog:控制输出,使其输出到一个缓冲区,这个缓冲区关联着定义在 <cstdio> 的 stderr. cerr:强制输出刷新,没有缓冲区. cout:控制输出,使其输出到一个缓冲区,这个 ...
- J2V8 For Android
J2V8是基于Google的JavaScript引擎V8的Java开源项目,实现Java和JavaScript的相互调用.并对Android平台提供支持,最新版本提供了aar格式的类库包方便Andro ...
- CentOS/Linux 网卡设置 IP地址配置
CentOS/Linux下设置IP地址 1:临时修改:1.1:修改IP地址# ifconfig eth0 192.168.100.100 1.2:修改网关地址# route add default g ...