哪位高人指点一下,C#中两个动态lambda 表达式有什么办法合并成一个? 谢谢!
展开全部
class Program
{
static void Main(string[] args)
{
C[] cs = new C[]{
new C(11),new C(22),new C(33),
new C(44),new C(55),new C(66)};
Expression<Func<C, bool>> e1 = x => x.N > 20;
Expression<Func<C, bool>> e2 = x => x.N < 50;
Expression<Func<C, bool>> e3 = e1.AndAlso(e2);
var re = cs.Where(e3.Compile()).ToArray();
foreach (C c in re)
Console.WriteLine(c.N);
//22 33 44
Console.ReadLine();
}
}
//元素类型定义
class C
{
public C(int n) { this.N = n; }
public int N;
}
//扩展方法
public static class Ext
{
public static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> a,
Expression<Func<T, bool>> b)
{
var p = Expression.Parameter(typeof(T), "x");
var bd = Expression.AndAlso(
Expression.Invoke(a, p),
Expression.Invoke(b, p));
var ld = Expression.Lambda<Func<T, bool>>(bd, p);
return ld;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询