【发布时间】:2019-04-14 09:26:32
【问题描述】:
我使用linqToEntities 并想动态添加OR 条件。
我知道there is a great library PredicateBuilder by brother Albahari 可以解决我的任务,但我不能使用它。
我的情况如下:
IEnumerable<Condition> conditions = new List<Condition>()
{
new Condition(){IdReference = 1, TableName = "Table1" },
new Condition(){IdReference = 2, TableName = "Table2" },
new Condition(){IdReference = 3, TableName = "Table3" },
// and so on
};
我拥有的是:
var histories = db.History as IQueryable<History>;
foreach (var cond in conditions)
{
//What code should be here to be translated into:
/*
histories = histories
.Where(h => h.IdReference == 1 && h.TableName =="Table1"
|| h.IdReference == 2 && h.TableName == "Table2"
|| h.IdReference == 3 && h.TableName == "Table3");
// and so on
*/
}
但是,我事先不知道conditions 会有多少。
如何从IEnumerable<Condition> 动态添加OR 条件?
【问题讨论】:
-
如果您没有太多组合,只需使用一些条件:
if(thisIsTheCase){ histories = histories.Where(// put your conditions} else if(another Case){ histories = histories.Where(// put your conditions}add more if else,直到您涵盖所有情况。您也可以通过创建动态表达式来做到这一点,但这并不容易,因为您需要组合表达式。 -
为什么不能使用
PredicateBuilder? -
@CodingYoshi 因为我的代码不会通过代码审查。
标签: c# entity-framework linq entity-framework-6 linq-to-entities