现在的位置: 首页 > 综合 > 正文

c#编程指南(二) LINQ表达式 (LINQ Expression)

2012年12月22日 ⁄ 综合 ⁄ 共 1249字 ⁄ 字号 评论关闭

C# 3.0 带来了强大的基于方法的查询LINQ。为了开发者更好更方便的使用LINQ,微软有随即引入两个新特性:

Lambda和Expression。Lambda简单来说就是一个匿名方法的简略写法,Expression和Lambda的关系可以从

下面的一小段代码看下:(.NET Framework 3.5, 记住引用命名空间System.Linq.Expressions;)

 

1 //simple express: 2 + 3
2   Expression e = Expression.Add(Expression.Constant(2), Expression.Constant(3));
3 //lambda express: () => 2 + 3;
4   LambdaExpression l = Expression.Lambda(e, null);
5 //compile to delegate.
6   Delegate d = l.Compile();
7 //convert to
8   Func<int> f = (Func<int>)d;
9 //
10  
11 Console.WriteLine(e);
12 Console.WriteLine(l);
13 Console.WriteLine(d);
14 Console.WriteLine(f());

 

输出结果为下:

 

1 (2 + 3)
2 () => (2 + 3)
3 System.Func`1[System.Int32]
4  5

 

 

 

第一个就是构造了一个简单的常数相加表达式,

第二个使用lambda形式表达。

第三个系统把lambda表达式编译成一个委托,注意这个委托是一个泛型委托形式。

第四个使用委托调用函数,输出结果 2 + 3 = 5,是不是很简单啊。

 

 

下面来一个从上面稍微改进,带参数的LINQ表达式:

1 ParameterExpression p = Expression.Parameter(typeof(int), "x");
2 //expression: x + 3
3   Expression e2 = Expression.Add(p, Expression.Constant(3));
4 //Lambda: x => x + 3;
5   LambdaExpression l2 = Expression.Lambda(e2, new ParameterExpression[] { p });
6 Delegate d2 = l2.Compile();
7 Func<int, int> f2 = (Func<int, int>)d2;
8
9 Console.WriteLine(e2);
10 Console.WriteLine(l2);
11 Console.WriteLine(d2);
12 Console.WriteLine(f2(3));

 

这个只是多使用了一个ParameterExpression,就是声明了一个参数。第一个例子是无参函数,那么这个就是简单的带一个参数的表达式。结果如下:

(x + 3)
x
=> (x + 3)
System.Func`
2[System.Int32,System.Int32]
6

 

很简单吧。

示例代码:下载

 

 

抱歉!评论已关闭.