我想为以下情况创建一个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; }
}

Csharp相关问答推荐

如何将ref T*重新解释为ref nint?

利用.NET 8中的AddStandardResilienceDeliveries和AddStandardHedgingDeliveries实现Resiliency

更新数据库中的对象失败,原因是:Microsoft. EntityFrame Core. GbUpdateConcurrencyResponse'

图形.DrawString奇怪异常的字距调整

EF Core判断是否应用了AsSplitQuery()

有没有办法把+02:00转换成TimeSpan?""

如何告诉自己创建的NuGet包在应用程序中发生了变化?

NumPy s fftn in C#with pythonnet'

MudBlazor—MudDataGrid—默认过滤器定义不允许用户修改基本过滤器

try 在Blazor项目中生成html

如何解决提交按钮后 Select 选项错误空参照异常

如何在C#中实现非抛出`MinBy`?

DateTime ToString()未以指定格式打印

该函数不能检测两条曲线的交点

数据库.Migrate在对接容器重启时失败

我想根据姓氏按字母顺序对包含150行徽章编号、姓氏、名字、地址等的文件进行排序.e

多个参数的最小API删除

无效的Zip文件-Zip存档

SignalR跨域

有没有更好的方法来使用LINQ获取整行的计算组