我使用下面的代码根据动态列名过滤记录

string[] colNames = {"firstName", "lastName", "Col3", "col4"}
string[] colValues = {"jac", "sam", "col3value","col4value"}

ParameterExpression param = Expression.Parameter(typeof(Student), "t");
MemberExpression column = Expression.Property(param, colNames[0]);
ConstantExpression searchValue = Expression.Constant(colValues[0]);
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
Expression exp = Expression.Call(column, containsMethod, searchValue);
var deleg = Expression.Lambda<Func<Student, bool>>(exp, param).Compile();

var students = context.StudentModel.Where(deleg).AsQueryable();

如何对多个列执行此操作(在我的示例中,将数组中的所有列合并在一起)

推荐答案

在本例中,基本方法是创建多个Expression.Call,并按照Svyatoslav Danyliv的建议将这些调用与Expression.AndAlso结合起来.

它们必须共享相同的参数.

因此,解决方案如下:

ParameterExpression param = Expression.Parameter(typeof(Student), "s");
MethodInfo containsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });

Expression combinedExpression = null; // this will be passed to context.StudentModel.Where

for (int i = 0; i < colNames.Length; i++)
{
    MemberExpression column = Expression.Property(param, colNames[i]);
    ConstantExpression searchValue = Expression.Constant(colValues[i]);

    Expression expression = Expression.Call(column, containsMethod, searchValue);

    combinedExpression = combinedExpression == null
        ? expression;
        : Expression.AndAlso(combinedExpression, expression);
}

您不需要编译combinedExpression,因为.Where请求Expression<Func<...>>,而不是Func本身.

`var students=上下文.学生模型.其中(组合表达式);

为了让所有过滤器正常工作,我假设您需要为不同类型创建单独的表达式,例如intint?,以判断它们是否相等(或>;、=>;等).因为目前Contains的使用非常有限.

另外,确保在colNames数组中有正确的property个名称,否则在Expression.Property调用时会出现错误.

.net相关问答推荐

无法在Designer、VS2022、. NET 8中打开WinForms表单'

如何使用.NET8MapIdentityApi设置OpenApi操作ID

在 .NET 7 项目上设置 Sentry 时遇到问题

为什么解码后的字节数组与原始字节数组不同?

是否必须使用 Visual Studio 预览才能使用 MAUI?

MongoDB GridFs with C#,如何存储图片等文件?

lock() 是否保证按请求的顺序获得?

是否可以模拟 .NET HttpWebResponse?

如何让 DateTimePicker 显示一个空字符串?

如何使用 NUnit(或可能使用另一个框架)测试异步方法?

实体框架 - 无法将 lambda 表达式转换为类型字符串,因为它不是委托类型

如何在 C# 中仅设置 DateTime 变量的时间部分

寻找 .NET 的命令行参数解析器

Dapper 是否支持 SQL 2008 表值参数?

Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher

是否可以判断对象是否已附加到实体框架中的数据上下文?

如何使用 NPOI 读取文件

WPF中的依赖属性和附加属性有什么区别?

System.ServiceModel 在 .NET Core 项目中找不到

App.config:用户与应用程序范围