开发者

Concatenate where queries with or operator in a QueryBuilder

开发者 https://www.devze.com 2023-04-07 12:29 出处:网络
QueryBuilder is defined in Microsoft.Windows.Data.DomainServices. It allows you to create a Query on a collection of type T and apply it later.

QueryBuilder is defined in Microsoft.Windows.Data.DomainServices. It allows you to create a Query on a collection of type T and apply it later.

When I need to concatenate where queries by && it is easy, for example you can do

        var query = new QueryBuilder<Customer>();

        if (!string.IsNullOrEmpty(this.CustomerFirstName))
            query = query.Where(c => c.FirstName == this.CustomerFirstName);

        if (!string.IsNullOrEmpty(this.CustomerLastName))
            query = query.Where(c => c.LastName == this.CustomerLastName);

        if (!string.IsNullOrEmpty(this.CustomerPhone))
            query = query.Where(c => c.Phone == this.CustomerPhone);

        if (!string.IsNullOrEmpty(this.CustomerMail))
            query = query.Where(c => c.Mail == this.CustomerMail);

I can't find out how should I concatenate those Where queries by || (or)??

I have a query that loads all Products in a database, since products are organized by category and a user can select only a sub-set of categories (the one he is interested in) I would like to load only products in categories that the user has specified

I know I could do it concatenating Where() by && where I exclude unselected categories example

 query.Where(c => c.CategoryName != "MyCategory");

but I don't like it.

I would like to do it in a foreach loop

private void LoadProducts()
{
     var query = new QueryBuilder<Product>();

     //Get Only Products in specified categories
     if (!string.IsNullOrEmpty(WebContext.Current.User.SelectedCat开发者_StackOverflowegoriesCSV))
     {

         foreach (string cat in WebContext.Current.User.SelectedCategoriesCSV.Split(';'))
         {
               ????//query.Where(c => c.CategoryName == cat || );
         }

     }

 .....


You need to dynamically build your where expression and then pass it once to the query.Where(). Check out the PredicateBuilder that provides Or method to accomplish that. Hope this helps.


You can use Dynamic LINQ operator that are available at this link: http://msdn.microsoft.com/en-us/bb330936.aspx (download the c# example and get the code in the \LinqSamples\DynamicQuery directory)


You can use PredicateBuilder class developed by Monty’s Gush.

Try this.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号