如何使用表达式树编写 List All 方法?
How to write List All method using expression trees?
我有以下代码片段。
var list= new List<CustomClass>(){ new CustomClass(){Id=10}};
var result= list.All(a=>a.Id==10);
我们如何将它写在表达式树中?
目的:它是我们正在实现的更大的表达式树逻辑的一部分,我只是坚持为列表的 "All" 方法生成表达式树。
谢谢
不太清楚您要做什么,但让我们从这里开始...
这是Enumerable.All
方法:
static readonly MethodInfo allTSource = (from x in typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
where x.Name == nameof(Enumerable.All)
let args = x.GetGenericArguments()
where args.Length == 1
let pars = x.GetParameters()
where pars.Length == 2 &&
pars[0].ParameterType == typeof(IEnumerable<>).MakeGenericType(args[0]) &&
pars[1].ParameterType == typeof(Func<,>).MakeGenericType(args[0], typeof(bool))
select x).Single();
然后.All(...)
中使用的lambda表达式:
// a =>
var par = Expression.Parameter(typeof(CustomClass), "a");
// a.Id
var id = Expression.Property(par, nameof(CustomClass.Id));
// 10
var val = Expression.Constant(10);
// a.Id == 10
var eq = Expression.Equal(id, val);
// a => a.Id == 10
var lambda = Expression.Lambda<Func<CustomClass, bool>>(eq, par);
然后是问题:不清楚 list
是常量还是外部表达式...我不知道如何将我的代码连接到您的代码...为了简单起见它是一个常数:
// Unclear what lst should be, a parameter of an external lambda or a constant
var lst = Expression.Constant(list);
// list.All(...)
var all = Expression.Call(allTSource.MakeGenericMethod(typeof(CustomClass)), lst, lambda);
// () => list.All(...)
Expression<Func<bool>> exp = Expression.Lambda<Func<bool>>(all);
Func<bool> fn = exp.Compile();
bool res = fn();
我有以下代码片段。
var list= new List<CustomClass>(){ new CustomClass(){Id=10}};
var result= list.All(a=>a.Id==10);
我们如何将它写在表达式树中?
目的:它是我们正在实现的更大的表达式树逻辑的一部分,我只是坚持为列表的 "All" 方法生成表达式树。
谢谢
不太清楚您要做什么,但让我们从这里开始...
这是Enumerable.All
方法:
static readonly MethodInfo allTSource = (from x in typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public)
where x.Name == nameof(Enumerable.All)
let args = x.GetGenericArguments()
where args.Length == 1
let pars = x.GetParameters()
where pars.Length == 2 &&
pars[0].ParameterType == typeof(IEnumerable<>).MakeGenericType(args[0]) &&
pars[1].ParameterType == typeof(Func<,>).MakeGenericType(args[0], typeof(bool))
select x).Single();
然后.All(...)
中使用的lambda表达式:
// a =>
var par = Expression.Parameter(typeof(CustomClass), "a");
// a.Id
var id = Expression.Property(par, nameof(CustomClass.Id));
// 10
var val = Expression.Constant(10);
// a.Id == 10
var eq = Expression.Equal(id, val);
// a => a.Id == 10
var lambda = Expression.Lambda<Func<CustomClass, bool>>(eq, par);
然后是问题:不清楚 list
是常量还是外部表达式...我不知道如何将我的代码连接到您的代码...为了简单起见它是一个常数:
// Unclear what lst should be, a parameter of an external lambda or a constant
var lst = Expression.Constant(list);
// list.All(...)
var all = Expression.Call(allTSource.MakeGenericMethod(typeof(CustomClass)), lst, lambda);
// () => list.All(...)
Expression<Func<bool>> exp = Expression.Lambda<Func<bool>>(all);
Func<bool> fn = exp.Compile();
bool res = fn();