您可以使用谓词构建器(实用程序类):
using System;
using System.Linq;
using System.Linq.Expressions;
public static class PredicateBuilder {
public static Expression<Func<T, bool>> Make<T>() {
return null;
}
public static Expression<Func<T, bool>> Make<T>(this Expression<Func<T, bool>> predicate) {
return predicate;
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> orExpression) {
if (expr == null) {
return orExpression;
}
var invokedExpr = Expression.Invoke(orExpression, expr.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.Or(expr.Body, invokedExpr), expr.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> andExpression) {
if (expr == null) {
return andExpression;
}
var invokedExpr = Expression.Invoke(andExpression, expr.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.And(expr.Body, invokedExpr), expr.Parameters);
}
}
用法:
public IEnumerable<Squad> GetSquadsByIDs(IEnumerable<int> squadIDs) {
if (squadIDs == null || !squadIDs.Any()) {
throw new ArgumentNullException("squadIDs");
}
var condition = PredicateBuilder.Make<Squad>(s => false);
foreach (var squadID in squadIDs) {
int squadIDValue = squadID;
condition = PredicateBuilder.Or<Squad>(condition, s => s.SquadID == squadIDValue);
}
var db = m_DalContextProvider.GetContext();
return db.Squads.Where(condition);
}