带有列表参数的表达式树

问题描述 投票:0回答:1

我想为以下情况创建一个 C# 表达式树:

EntityA.Where(x => list.Any(y => y == x.SomeProperty))

我做了一些尝试,在网上找到了一些类似的例子,但没有一个与上面完全一样。

如有任何建议、参考、解决方案,我们将不胜感激。

c# list lambda tree expression
1个回答
0
投票
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");
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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.