Expression<Func<Student, bool>> filter=s=>s.Name.Contains("a") && s.Age>=20;

这样的表达试转换成

Expression<Func<DataRow, bool>> filter = r=>((string)r["Name"]).Contains("a") && ((int)r["Age"])>=20;

也许你会问,干嘛要这样做呢?举个例子,

说DAL里有一个类StudentProvider用于对student进行数据库的增删改查的操作。我们就拿查询来说,查询可以有很多的条件。以往可能会有类似的方法:

public IEnumerable<Student> GetStudentsByName(string name);
public Student GetStudentById(int id);

但是别忘了今天的世界有了Expression,我们应该向这些落后的(别打我,窃以为的)方法说再见了。高颜值的接口当然要写成这样了:

public IEnumerable<Student> GetStudents(Expression<Func<Student, bool>> filter);

于是我们来看看这个方法的实现,

     public IEnumerable<Student> GetStudents(Expression<Func<Student, bool>> filter)
{
using (var connection=new SqlConnection("some connection string"))
{
var selectSql = "SELECT * FROM Student";
using (var adapter = new SqlDataAdapter(selectSql, connection))
{
var ds = new DataSet();
adapter.Fill(ds, "table");
return from raw in ds.Tables["table"].AsEnumerable() select new Student(raw);
}
}
}

实现用到了Linq to DataSet, 其实我们真正想做的是

return from raw in ds.Tables["table"].AsEnumerable().Where(filter) select new Student(raw)

但是问题是Where只接受

Func<DataRow, bool> predicate

到这里,终于明白了为什么要做LambdaExpression变换了吧。

前一篇中我们看到了ExpressionVisitor的强大,这里我们还要用他来解决问题。我们引入一个ConvertMemberToColumnVisitor:

     public class ConvertMemberToColumnVisitor : ExpressionVisitor
{
private readonly Expression _columnOwnerExpression;
private readonly string _memberOwnerName; public ConvertMemberToColumnVisitor(Expression columnOwnerExpression, string memberOwnerName)
{
_columnOwnerExpression = columnOwnerExpression;
_memberOwnerName = memberOwnerName;
} protected override Expression VisitMember(MemberExpression node)
{
var parameterExpression = node.Expression as ParameterExpression;
if (parameterExpression != null && parameterExpression.Name == _memberOwnerName)
{
return Expression.Convert(Expression.Call(_columnOwnerExpression, typeof(DataRow).GetMethod("get_Item", new []{typeof(string)}), Expression.Constant(node.Member.Name)),
((PropertyInfo)node.Member).PropertyType);
} return base.VisitMember(node);
}
}

很简单,很定一个我们要替代成的表达式,当然我们还是用parameter name来匹配所以要给定一个参数名。

有了这个Visitor后,一切问题都简单了:

     public IEnumerable<Student> GetStudents(Expression<Func<Student, bool>> filter)
{
using (var connection=new SqlConnection("some connection string"))
{
var selectSql = "SELECT * FROM Student";
using (var adapter = new SqlDataAdapter(selectSql, connection))
{
var ds = new DataSet();
adapter.Fill(ds, "table"); var p1 = Expression.Parameter(typeof(DataRow), "r");
var converter = new ConvertMemberToColumnVisitor(p1, filter.Parameters[0].Name);
var newExp = converter.Visit(filter);
var lambda = Expression.Lambda<Func<DataRow, bool>>(((LambdaExpression)newExp).Body, p1);
var predicate = lambda.Compile();
return from raw in ds.Tables["table"].AsEnumerable().Where(predicate) select new Student(raw);
}
}
}

Lamda Expression的更多相关文章

  1. Does Lamda expression return value?

    Basically, the compiler does this for you. If you write a lambda as a single statement (and don't in ...

  2. Expression Tree Basics 表达式树原理

    variable point to code variable expression tree data structure lamda expression anonymous function 原 ...

  3. 论C#未来发展

    近日M#的消息令江湖再次起了波澜.大家知道,.NET已经进入了瓶颈期.这个消息又让偶有所期待,趁此机会发表一下个人的展望,对C#或者其继任者,不管是M#还是X#. 一.语法特性 1. using引入类 ...

  4. 数学符号π (Pi)、Σ(Capital Sigma)、μ (Mu) 、σ(sigma)、∏(capital pi), ∫(Integral Symbol)的来历

    1.π (Pi; periphery/周长) March 14 marks Pi Day, the holiday commemorating the mathematical constant π ...

  5. Java learning notes (1):Basic Knowlege points

    Basic Knowlege points: 1: it's necessary that there is only one public class in per .java file 2: .j ...

  6. IMPLEMENTATION - Entity Framework Anti Pattern - High Performance EF

    Good about ORM Developer is free from building T-Sql on the database tier which is not their major a ...

  7. Python 与 Javascript 之比较

    最近由于工作的需要开始开发一些Python的东西,由于之前一直在使用Javascript,所以会不自觉的使用一些Javascript的概念,语法什么的,经常掉到坑里.我觉得对于从Javascript转 ...

  8. Unity在WPF中的应用

    1. 本文的实现类继承于IRepository using System; using System.Linq; using System.Linq.Expressions; using Zhang. ...

  9. [No000012E]WPF(6/7):概念绑定

    WPF 的体系结构,标记扩展,依赖属性,逻辑树/可视化树,布局,转换等.今天,我们将讨论 WPF 最重要的一部分——绑定.WPF 带来了优秀的数据绑定方式,可以让我们绑定数据对象,这样每次对象发生更改 ...

随机推荐

  1. mobile_点透_传透_touch-action

    点透(传透) <meta name="viewport" content="width=device-width, initial-scale=1.0, user- ...

  2. viewport的故事(二)

     挑重点的翻译 自原文 https://www.quirksmode.org/mobile/viewports2.html   在这一页我们将聊一聊移动端的浏览器.   移动端的问题   最明显的问题 ...

  3. python +selenium +chrome/firefox 环境配置

    http://ftp.mozilla.org/pub/firefox/releases/ 各firefox版本下载地址 http://ftp.mozilla.org/pub/firefox/relea ...

  4. 问题:怎么把mysql的系统时间调整为电脑的时间?(已解决)

    我的mysql是5.7版本. 浏览mysql的错误日志的时候,发现时间和电脑时间不一致. 查了一下,知道这个时间和log_timestamps有关, 就在mysql里执行下面一句话: SET GLOB ...

  5. 2018-2019-2 网络对抗技术 20165311 Exp2 后门原理与实践

    2018-2019-2 网络对抗技术 20165311 Exp2 后门原理与实践 后门的基本概念 常用后门工具 netcat Win获得Linux Shell Linux获得Win Shell Met ...

  6. 为Vue.js添加友好日志

    const isDebugEnabled = process.env.NODE_ENV !== "production"; const isInfoEnabled = true; ...

  7. $_SERVER服务器端

    url = 'http://www.5idev.com/php/index.php/test/foo?username=hbolive' php 获取$_SERVER信息 $_SERVER['PHP_ ...

  8. socks-proxy---with ssh

    socks-proxy---with sshhttps://blog.csdn.net/scien2011/article/details/54562501

  9. ionic3 添加多个自定义组件

    往往我们创建自定义组件一般都不止只会创建一个自定义组件,创建多个方式如下. 1.创建自定义组件 ionic g component select-car-no ionic g component ae ...

  10. GridFS and Geospatial

    GridFS - specification for storing and retrieving large files... images,audio file, video files... F ...