我知道这很有趣且令人兴奋(讽刺),但您可以像这样动态构建您的 Where 表达式:
var serviceNames = new string[] { "SERVICE1","SERVICE2"};
Expression<Func<Service,bool>> inList = v => false;
var parameter = inList.Parameters[0];
var propertyExpression = Expression.Property(parameter,"ServiceName");
foreach (var serviceName in serviceNames)
{
var body = inList.Body;
var constantExpression = Expression.Constant(serviceName);
var equalityExpression = Expression.Equal(propertyExpression,constantExpression);
body = Expression.OrElse(body,equalityExpression);
inList = Expression.Lambda<Func<Service, bool>>(body, parameter);
}
IEnumerable<Service> services = context.Services.Expand(ServiceQueryExpansion)
.Where(inList);
此方法从您的列表中构建一个自定义 where 子句,类似于 (v => v.ServiceName == "Service1" || v.ServiceName == "Service2" || v.ServiceName == "Service3")
您可能可以按照我的博客https://secureapplicationlifestyle.com/2013/07/filter-pattern-for-linq-query-filter.html中的指示将此逻辑封装到自定义“WhereContains(yourListHere)”自定义过滤器扩展中方法。