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 _ ...
随机推荐
- 嵌入式Linux系统挂载NFS系统
在建立交叉编译环境的时候,经常需要网嵌入式Linux环境中拷贝文件,nfs网络共享文件系统是一种很方便的方式. 在嵌入式Linux挂载nfs系统,需要用到如下命令: mount -t nfs -o n ...
- table表格frame属性
定义和用法 frame 属性规定外侧边框的哪个部分是可见的. 从实用角度出发,最好不要规定 frame,而是使用 CSS 来添加边框样式. 浏览器支持 除了 Internet Explorer,其他浏 ...
- laravel 带条件的分页查询
laravel 带条件的分页查询, 原文:http://blog.csdn.net/u011020900/article/details/52369094 bug:断点查询,点击分页,查询条件消失. ...
- 【leetcode 简单】 第九十九题 字符串相加
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和. 注意: num1 和num2 的长度都小于 5100. num1 和num2 都只包含数字 0-9. num1 和num2 都不包 ...
- JavaScript数组的概念
数组 1.数组是什么? 数组就是一组变量存放在里面就是数组. 例如:var list=['apple','goole','alibaba',520] (1.这些数据有一些相关性的. ( ...
- Python练习-迭代器-模拟cat|grep文件
代码如下: # 编辑者:闫龙 def grep(FindWhat): f=open("a.txt","r",encoding="utf8") ...
- 收集了一些python的文章
来自: 戴铭 2010-08-31 17:52:31 newthreading - safer concurrency for Python 安全并发(1回应) http://www.starming ...
- 【CTF WEB】GCTF-2017读文件
读文件 只给了个1.txt可以读,试了一下加*不行,感觉不是命令执行,"../"返回上级目录也不行,猜测可能过滤了什么,在1.txt中间加上"./"发现仍能读取 ...
- python socket编程入门级
客户端 import socket import time sk = socket.socket() # 第一步:创建socket对象 address = ('127.0.0.1', 8080) # ...
- c++语言知识点汇总
c++ primer version-5 的整理 section 1: 内置类型和自定义类型: main函数的返回值:指示状态.0:成功:1:系统定义. unix和win系统中,执行完程序可以使用ec ...