C#之Expression表达式树实例
本文实例讲述了c#之expression表达式树,分享给大家供大家参考。具体实现方法如下:
表达式树表示树状数据结构的代码,树状结构中的每个节点都是一个表达式,例如一个方法调用或类似 x < y 的二元运算
1.利用 lambda 表达式创建表达式树
2.编译表达式树,该方法将表达式树表示的代码编译成一个可执行委托
3.iqueryable<t>的扩展方法,wherein的实现
完整代码如下:
using mongodb.driver;
using mongodb.driver.builders;
using system;
using system.collections.generic;
using system.linq;
using system.linq.expressions;
using system.text;
using system.threading.tasks;
namespace mongodbtest
{
class program
{
static void main(string[] args)
{
//使用lambdaexpression构建表达式树
expression<func<int, int, int, int>> expr = (x, y, z) => (x + y) / z;
console.writeline(expr.compile()(1, 2, 3));
//使用lambdaexpression构建可执行的代码
func<int, int, int, int> fun = (x, y, z) => (x + y) / z;
console.writeline(fun(1, 2, 3));
//动态构建表达式树
parameterexpression pe1 = expression.parameter(typeof(int), "x");
parameterexpression pe2 = expression.parameter(typeof(int), "y");
parameterexpression pe3 = expression.parameter(typeof(int), "z");
var body = expression.divide(expression.add(pe1, pe2), pe3);
var w = expression.lambda<func<int, int, int, int>>(body, new parameterexpression[] { pe1, pe2, pe3 });
console.writeline(w.compile()(1, 2, 3));
list<entity> list = new list<entity> { new entity { id1 = 1 }, new entity { id1 = 2 }, new entity { id1 = 3 } };
var d = list.asqueryable().wherein(o => o.id1, new int[] { 1, 2 });
d.tolist().foreach(o =>
{
console.writeline(o.id1);
});
console.readkey();
}
}
public class entity
{
public objectid id;
public int id1;
public string name { get; set; }
}
public static class cc
{
public static iqueryable<t> wherein<t, tvalue>(this iqueryable<t> query, expression<func<t, tvalue>> obj, ienumerable<tvalue> values)
{
return query.where(buildcontainsexpression(obj, values));
}
private static expression<func<telement, bool>> buildcontainsexpression<telement, tvalue>(expression<func<telement, tvalue>> valueselector, ienumerable<tvalue> values)
{
if (null == valueselector)
{
throw new argumentnullexception("valueselector");
}
if (null == values)
{
throw new argumentnullexception("values");
}
var p = valueselector.parameters.single();
if (!values.any()) return e => false;
var equals = values.select(value => (expression)expression.equal(valueselector.body, expression.constant(value, typeof(tvalue))));
var body = equals.aggregate(expression.or);
return expression.lambda<func<telement, bool>>(body, p);
}
}
}
希望本文所述对大家的c#程序设计有所帮助。