Creating a common predicate function

前端 未结 5 1294
南方客
南方客 2020-12-14 01:17

Firstly, I am not sure what terms to use to ask this question, which is probably why I have not found an answer from searching myself.

So I am working with Linq to S

5条回答
  •  旧巷少年郎
    2020-12-14 01:51

    The neat thing about how LINQ to SQL handles expressions is that you can actually build out expressions elsewhere in your code and reference them in your queries. Why don't you try something like this:

    public static class Predicates
    {
        public static Expression> CheckForFlags()
        {
            return (user => user.Flag1 || user.Flag2 || user.Flag3 ||
                            user.Flag4 || user.Flag5);
        }
    
        public static Expression> CheckForCriteria(string value)
        {
            return (user => user.Criteria1 == value);
        }
    }
    

    Once you have your predicates defined, it's very easy to use them in a query.

    var users = DataContext.Users
        .Where(Predicates.CheckForFlags())
        .Where(Predicates.CheckForCriteria("something"));
    

提交回复
热议问题