Linq dynamically adding where conditions

前端 未结 3 378
一生所求
一生所求 2020-12-03 16:23

I have a gridview which has drop down boxes in each header for filtering. Each filter is loaded with the distinct values from its column when loaded. At run time, I add \"AL

相关标签:
3条回答
  • 2020-12-03 17:02

    Create extension method(s) which encapsulate the where logic so it looks cleaner:

    var filteredList = allQuotes.WhereDropOwnersAreContained()
                                .WhereCompanyIsContained()
                                ...
                                ;
    
    0 讨论(0)
  • 2020-12-03 17:08

    You could create a helper method that handles the All logic. Something like:

    private bool CompareSelectedValue(string value, string dropDownValue)
    {
      if(dropDownValue == "ALL")
        return true;
      else
        return value == dropDownValue;
    }
    

    Then your query could be:

    var filteredList = (from x in allQuotes
                              where (CompareSelectedValue(x.SalesRepFullName, drpOwners.SelectedValue)                                    
                                    && CompareSelectedValue(x.CompanyName, drpCompanyName.SelectedValue)
                              select x);
    
    0 讨论(0)
  • Personally, I'd find having this broken up to be simpler:

    IEnumerable<Quote> filteredList = allQuotes;
    // If using EF or LINQ to SQL, use: IQueryable<Quote> filteredList = allQuotes;
    if (drpOwners.SelectedValue != ALL) 
       filteredList = filteredList.Where(x => x.SalesRepFullName == drpOwners.SelectedValue);
    if (drpCompanyName.SelectedValue != ALL) 
       filteredList = filteredList.Where(x => x.CompanyName == drpCompanyName.SelectedValue);
    // More conditions as needed
    

    This really isn't any longer, and it's far simpler to follow.


    If you really wanted to be able to write this as a "one-liner", you could make an extension method to build the query. For example, if using Entity Framework:

    static IQueryable<T> AddCondition(this IQueryable<T> queryable, Func<bool> predicate, Expression<Func<T,bool>> filter)
    {
         if (predicate())
             return queryable.Where(filter);
         else
             return queryable;
    }
    

    This would then let you write this as:

    var filteredList = allQuotes
                         .AddCondition(() => drpOwners.SelectedValue != ALL, x => x.SalesRepFullName == drpOwners.SelectedValue)
                         .AddCondition(() => drpCompanyName.SelectedValue != ALL, x.CompanyName == drpCompanyName.SelectedValue);
    

    You could, of course, take this even further, and make a version that hard-wires the predicate to check a combo box against "ALL", making the predicate shorter (just the combo box).

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