http://www.cnblogs.com/ldp615/archive/2011/09/15/expression-extension-methods.html

.net 中创建 Expression Trees 最简单的方式是使用 lambda
表达式:

1
2
Expression<Func<Person, bool>> exp =
p => p.Name.Contains("ldp") && p.Birthday.Value.Year > 1990;

其中 Person 类定义如下:

1
2
3
4
public class Person {
public string Name { get; set; }
public DateTime? Birthday { get; set; }
}

但有些时候,要动态创建 Expression Trees,我们要用到 System.Linq.Expressions 命名空间中的 Expression

使用 Expression 类 中的静态方法,前面的 Expression
Trees
 可如下创建:

1
2
3
4
5
6
7
8
9
10
var parameter = Expression.Parameter(typeof(Person), "p");
var left = Expression.Call(
Expression.Property(parameter, "Name"),
typeof(string).GetMethod("Contains"),
Expression.Constant("ldp"));
var right = Expression.GreaterThan(
Expression.Property(Expression.Property(Expression.Property(parameter, "Birthday"), "Value"), "Year"),
Expression.Constant(1990));
var body = Expression.AndAlso(left, right);
var lambda = Expression.Lambda<Func<Person, bool>>(body, parameter);

你应该注意到第 7 行高亮部分,三个重复的 Expression.Property,显得非常臃肿,导致可读性也很差。

可以用下面几个扩展方法予以简化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static class ExpressionExtensions {
public static Expression AndAlso(this Expression left, Expression right) {
return Expression.AndAlso(left, right);
}
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments) {
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
}
public static Expression Property(this Expression expression, string propertyName) {
return Expression.Property(expression, propertyName);
}
public static Expression GreaterThan(this Expression left, Expression right) {
return Expression.GreaterThan(left, right);
}
public static Expression<TDelegate> ToLambda<TDelegate>(this Expression body, params ParameterExpression[] parameters) {
return Expression.Lambda<TDelegate>(body, parameters);
}
}

这五个扩展方法相当简单,没什么技术含量。可以根据自己需要,添加更多的扩展方法。

前面的代码简化成:

1
2
3
4
var parameter = Expression.Parameter(typeof(Person), "p");
var left = parameter.Property("Name").Call("Contains", Expression.Constant("ldp"));
var right = parameter.Property("Birthday").Property("Value").Property("Year").GreaterThan(Expression.Constant(1990));
var lambda = left.AndAlso(right).ToLambda<Func<Person, bool>>(parameter);

是不是好多了。

简单编码,快乐生活!

c# 扩展方法奇思妙用基础篇九:Expression 扩展的更多相关文章

  1. c# 扩展方法奇思妙用基础篇八:Distinct 扩展(转载)

    转载地址:http://www.cnblogs.com/ldp615/archive/2011/08/01/distinct-entension.html 刚看了篇文章 <Linq的Distin ...

  2. c# 扩展方法奇思妙用基础篇八:Distinct 扩展

    刚看了篇文章 <Linq的Distinct太不给力了>,文中给出了一个解决办法,略显复杂. 试想如果能写成下面的样子,是不是更简单优雅 var p1 = products.Distinct ...

  3. c# 扩展方法奇思妙用基础篇五:Dictionary<TKey, TValue> 扩展

    Dictionary<TKey, TValue>类是常用的一个基础类,但用起来有时确不是很方便.本文逐一讨论,并使用扩展方法解决. 向字典中添加键和值 添加键和值使用 Add 方法,但很多 ...

  4. c# 扩展方法 奇思妙用 高级篇 九:OrderBy(string propertyName, bool desc)

    下面是 Queryable 类 中最常用的两个排序的扩展方法: 1 2 public static IOrderedQueryable<TSource> OrderBy<TSourc ...

  5. C# 扩展方法奇思妙用高级篇六:WinForm 控件选择器

    在Web开发中,jQuery提供了功能异常强大的$选择器来帮助我们获取页面上的对象.但在WinForm中,.Net似乎没有这样一个使用起来比较方便的选择器.好在我们有扩展方法,可以很方便的打造一个. ...

  6. c# 扩展方法奇思妙用

    # 扩展方法出来已久,介绍扩展方法的文章也很多,但都是笼统的.本人最近一直在思考扩展方法的应用,也悟出了一些,准备将这最近一段时间对扩展方法的思考,写成一个系列文章.每个文章只介绍一个应用方面,篇幅不 ...

  7. c# 扩展方法奇思妙用集锦

    本文转载:http://www.cnblogs.com/ldp615/archive/2009/08/07/1541404.html 其中本人觉得很经典的:c# 扩展方法奇思妙用基础篇五:Dictio ...

  8. 【mongoDB基础篇②】PHP-mongo扩展的编译以及使用

    安装PHP-mongo扩展 安装php-mongo扩展和安装其他php扩展的步骤一样: #1.首先上http://pecl.php.net上面搜索mongo,得到下载地址 wget http://pe ...

  9. Lua 学习之基础篇九<Lua 协同程序(Coroutine)>

    引言 讲到协程,首先来介绍一下线程和协程的区别 lua协程和多线程 相同之处:拥有自己独立的桟.局部变量和PC计数器,同时又与其他协程共享全局变量和其他大部分东西 不同之处:一个多线程程序可以同时运行 ...

随机推荐

  1. 字节跳动五面都过了,结果被刷了,问了hr原因竟说是...

    说在前面,面试时最好不要虚报工资.本来字节跳动是很想去的,几轮面试也通过了,最后没offer,自己只想到几个原因:1.虚报工资,比实际高30%:2.有更好的人选,这个可能性不大,我看还在招聘.我是面试 ...

  2. remote: Support for password authentication was removed

    周末提交代码,把代码push到github上,控制台报了下面的错误: remote: Support for password authentication was removed on August ...

  3. thunderbird发送纯文本邮件

    向邮件列表中发邮件时,要求邮件格式必须是纯文本格式的,在thunderbird中,邮件格式(plain text或者html格式)在[工具->账户设置->[账户名称]->通讯录]下的 ...

  4. Devcpp(Dev-C++)代码编辑的快捷键

    转自:https://blog.csdn.net/u010940020/article/details/43735549 这里记录一些个人使用Devcpp时,摸索出来的代码编辑快捷键,感觉非常有用.如 ...

  5. 长亭xray被动扫描

    为了实现点到哪里扫到哪里,用长亭xray配合burp suite插件 插件名为Passive Scan Client https://github.com/lilifengcode/Burpsuite ...

  6. 对象 绑定关系 隐藏属性 property 继承

    绑定方法两种: 1.绑定给对象的 class Student(): country = 'CHINA' def __init__(self,name,age): self.name = name se ...

  7. 深度学习框架如何自动选择最快的算法?Fast Run 让你收获最好的性能!

    作者:王博文 | 旷视 MegEngine 架构师 一.背景 对于深度学习框架来说,网络的训练/推理时间是用户非常看中的.在实际生产条件下,用户设计的 NN 网络是千差万别,即使是同一类数学计算,参数 ...

  8. net start mongodb 提示:发生系统错误 5,拒绝访问。

    问题: net start mongodb 提示:发生系统错误 5,拒绝访问. 无法启动mongodb 服务. 解决办法: 右键cmd,选择以管理员身份运行即可

  9. java简体(繁体)转换器

    <!--中文字符简繁体互相转换--> <dependency> <groupId>com.github.nobodxbodon</groupId> &l ...

  10. mfc HackerTools远程线程注入

    在一个进程中,调用CreateThread或CreateRemoteThreadEx函数,在另一个进程内创建一个线程(因为不在同一个进程中,所以叫做远程线程).创建的线程一般为Windows API函 ...