【问题标题】:C# dynamic predicate building [duplicate]C#动态谓词构建[重复]
【发布时间】:2020-02-26 13:15:41
【问题描述】:
有没有办法根据某个值动态构建谓词表达式?
class ClassObj
{
public int SomeValue { get; set; }
public int SomeOtherValue { get; set; }
}
例如,如果我有int val 和List<ClassObj>。例如,如果我的 val 等于 5,我希望我的列表只保留 SomeValue 等于 5 的对象。如果我的 val 等于其他值,我希望我的列表保留对象其SomeOtherValue 等于该数字。
【问题讨论】:
标签:
c#
linq
collections
predicate
【解决方案1】:
怎么样:
static Func<ClassObj, bool> GetValueFilter(int val) => val switch {
5 => x => x.SomeValue == 5, // or == val in the more general case
_ => x => x.SomeOtherValue == val,
};
(如果是用于 EF 等,则返回 Expression<Func<ClassObj, bool>>)
有用法:
var filtered = source.Where(GetValueFilter(val));
【解决方案2】:
Func<ClassObject, bool> predicate;
if (val == 5)
{
predicate = obj => obj.SomeValue == 5;
}
else
{
predicate = obj => obj.SomeOtherValue == val;
}
var result = yourList.Where(predicate);
当然,对于您的示例,您可以使用单个表达式:
yourList.Where(obj => val == 5 ? obj.SomeValue == 5 : obj.SomeOtherValue == val);