Search code examples
c#linqcollectionspredicate

C# dynamic predicate building


Is there a way to build a predicate expression dynamically depending on some value?

class ClassObj
{
    public int SomeValue { get; set; }
    public int SomeOtherValue { get; set; }
}

For example, if I have int val and a List<ClassObj>. If my val equals to 5, for example, I'd like my list to keep only objects whose SomeValue is equal to 5. If my val equals to something else, I'd like my list to keep objects whose SomeOtherValue is equal to that number.


Solution

  • How about:

    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,
    };
    

    (or return Expression<Func<ClassObj, bool>> if this is for EF etc)

    with usage:

    var filtered = source.Where(GetValueFilter(val));