我想为以下情况创建一个c#表达式树:
A.Where
我做了几次try ,在网上找到了几个类似的例子,但没有一个和上面的完全一样.
如有任何建议、参考、解决方案,将不胜感激.
我想为以下情况创建一个c#表达式树:
A.Where
我做了几次try ,在网上找到了几个类似的例子,但没有一个和上面的完全一样.
如有任何建议、参考、解决方案,将不胜感激.
using System.Linq.Expressions;
using System.Reflection;
// example data
IQueryable<Foo> source = Enumerable.Range(0, 10)
.Select(x => new Foo { SomeProperty = x })
.ToList().AsQueryable();
List<int> list = [ 1, 4 ];
// expression tree construction
var any = typeof(Enumerable)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.IsGenericMethodDefinition
&& m.Name == "Any"
&& m.GetParameters().Length == 2
).MakeGenericMethod(typeof(int));
var x = Expression.Parameter(typeof(Foo), "x"); // the type from "source"
var y = Expression.Parameter(typeof(int), "y"); // the type from "list"
var inner = Expression.Lambda<Func<int, bool>>(
Expression.Equal(y, Expression.Property(x, "SomeProperty")), y);
Console.WriteLine(inner);
var outer = Expression.Lambda<Func<Foo, bool>>(
Expression.Call(null, any, Expression.Constant(list), inner), x);
Console.WriteLine(outer);
var query = source.Where(outer);
// show it working
foreach (var item in query)
{
Console.WriteLine(item.SomeProperty);
}
class Foo
{
public int SomeProperty { get; set; }
}