How to dynamically build and return a linq predicate based on user input

后端 未结 2 391
没有蜡笔的小新
没有蜡笔的小新 2021-01-12 02:22

Getting a bit stuck on this. Basically I have a method that I want to return a predicate expression that I can use as a Where condition. I think what I need to do is simila

相关标签:
2条回答
  • 2021-01-12 02:29

    A predicate is only a function that returns a boolean value.

    I can not test it, right now, but wouldn't this work ?

    private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year)
    {
        if (!String.IsNullOrEmpty(keyword))
        {
            //return a filtering fonction
            return (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword)));
        }
        if (venueId.HasValue) 
        {
            // Some other predicate added...
            return (conf)=> /*something boolean here */;
        }
    
        //no matching predicate, just return a predicate that is always true, to list everything
        return (conf) => true;
    
    }
    

    EDIT : based on Matt's comments If you want to compose the delegates, you could proceed this way

    private static Expression<Func<Conference, bool>> GetSearchPredicate(string keyword, int? venueId, string month, int year)
    {   
        Expression<Func<Conference, bool> keywordPred = (conf) => true;
        Expression<Func<Conference, bool> venuePred = (conf) => true;
        //and so on ...
    
    
        if (!String.IsNullOrEmpty(keyword))
        {
            //edit the filtering fonction
            keywordPred =  (conf)=> conf.Title.Contains(keyword) || Description.Contains(keyword)));
        }
        if (venueId.HasValue) 
        {
            // Some other predicate added...
            venuePred =  (conf)=> /*something boolean here */;
        }
    
        //return a new predicate based on a combination of those predicates
        //I group it all with AND, but another method could use OR
        return (conf) => (keywordPred(conf) && venuePred(conf) /* and do on ...*/);
    
    }
    
    0 讨论(0)
  • 2021-01-12 02:48

    Have you checked out PredicateBuilder

    0 讨论(0)
提交回复
热议问题