我有一个场景使用下面的代码来简化这里的解释。我有一个模型类class Model{ public string CodeLevel1 { get; set; } public string CodeLevel2 { get; set; } public bool IsVoluntary { get; set; }}很明显,我将建立一个对象列表 var models = new List<Model> { new Model() { CodeLevel1 = "32", CodeLevel2 = "A1", IsVoluntary = false }, new Model() { CodeLevel1 = "32", CodeLevel2 = "A2", IsVoluntary = true }, new Model() { CodeLevel1 = "33", CodeLevel2 = "A3", IsVoluntary = true }, new Model() { CodeLevel1 = "34", CodeLevel2 = "A4", IsVoluntary = false }, new Model() { CodeLevel1 = "34", CodeLevel2 = "A5", IsVoluntary = false }, new Model() { CodeLevel1 = "34", CodeLevel2 = "A6", IsVoluntary = true }, };我想使用通用PredicateBuilder 中引入的PredicateBuilder来构建动态查询。以下代码只是我尝试的第一步。var configs = new Dictionary<string, List<string>>(){ { "32", new List<string>() { "A1", "A2"} }, { "33", new List<string>() { "A3" } },};var predicate = PredicateBuilder.False<Model>();var allLevel1CodesInConfig = (from c in configs select c.Key).ToList();predicate.Or(x => !allLevel1CodesInConfig.Contains(x.CodeLevel1) && x.IsVoluntary == false);var filteredList = models.AsQueryable().Where(predicate).ToList();我在 . 中什么也没得到filteredList,但是如果我重写最后一行代码,我就会得到我所期望的。var filteredList = models.AsQueryable().Where(x => !allLevel1CodesInConfig.Contains(x.CodeLevel1) && x.IsVoluntary == false).ToList();我需要一些帮助来理解为什么谓词 inWhere对我不起作用?
1 回答
元芳怎么了
TA贡献1798条经验 获得超7个赞
问题出在这一行:
predicate.Or(x => !allLevel1CodesInConfig.Contains(x.CodeLevel1) && x.IsVoluntary == false);
将其更改为:
predicate = predicate.Or(x => !allLevel1CodesInConfig.Contains(x.CodeLevel1) && x.IsVoluntary == false);
每种PredicateBuilder
方法都会创建一个新的谓词,并且不会改变原始谓词。
- 1 回答
- 0 关注
- 197 浏览
添加回答
举报
0/150
提交
取消