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

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相关问答推荐

SLN配置文件:映射问题

Azure管道-使用.NET 8 RC2 SDK生成C#项目失败

.NET 7.0中的UseHttpsRedirection和IIS生产部署

为什么 SortedSet.GetViewBetween 不是 O(log N)?

log4net 与 TraceSource

共享 AssemblyInfo 用于跨解决方案的统一版本控制

Winforms:Application.Exit vs Environment.Exit vs Form.Close

读取方法的属性值

如何使用转储文件来诊断内存泄漏?

修剪数组中的所有字符串

WCF服务客户端:内容类型text/html;响应消息的charset=utf-8 与绑定的内容类型不匹配

C#As的 VB.NET 类似功能

如何对 LINQ to XML 中的元素进行深层复制?

使用 C# 设置全局热键

将两个列表映射到 C# 中的字典中

找不到库 hostpolicy.dll

如何修复 .NET Windows 应用程序在启动时崩溃并出现异常代码:0xE0434352?

并发字典正确用法

Guid.Parse() 或 new Guid() - 有什么区别?

如何从 webclient 获取状态码?