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

最新文章

  1. Windows Azure HandBook (4) 分析Windows Azure如何处理Session
  2. 剑指Offer 二进制中1的个数
  3. 带你玩转JavaWeb开发之一 - HTML快速入门
  4. hibernate学习(设计一对多 关系 映射)
  5. iOS支付宝集成时遇到的问题整理(2)
  6. SQL Server服务器名称与默认实例名不一致的修复方法
  7. Android组件系列----Android Service组件深入解析
  8. mongo操作
  9. wait() 与 sleep
  10. .container_fluid 与 .container 的区别
  11. Java ArrayList操作
  12. Mac 与 PC 键盘布局对比
  13. Exchange模式功能
  14. Object-C属性(Properties)
  15. java设计模式演示样例
  16. 初学Java ssh之Spring 第一篇
  17. Qt部件--烧肉
  18. MyBatis使用DEMO及cache的使用心得
  19. JS - 点击 “+” 、“-” 改变数字
  20. WCF扩展之实现ZeroMQ绑定和protocolBuffer消息编码(三)实现ReplyChannel(2016-03-15 12:35)

热门文章

  1. Java编程思想 4th 第2章 一切都是对象
  2. 『实践』百度地图给多个marker添加右键菜单(删除、更新)
  3. Sublime Text 3 注册码失效(被移除)解决方法
  4. 目标板通过nfs挂载根文件系统
  5. mac下PHPStorm2018.2破解教程
  6. css 让背景图片不停旋转
  7. 首次加载进来DEV控件列表第一行颜色总是不对,后台代码显示的数据正确
  8. MySQL学习笔记:delete from与truncate table的区别
  9. How to tell your iPhone application that location services are required | The Agile Warrior
  10. Linux命令之远程登录与执行远程主机命令