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 "ALL" to allow the user to select all from that field. I am trying to build the linq statement dynamically to ignore the field if the drop down box is set to "ALL". Is this possible? I want to see if I can do this in one single statement. The example below only shows 2 dropdown boxes, but my actually case has up to 5.
If I choose to use if then statements, I end up with spaghetti code.
DropDownList drpOwners = this.grdOtherQuotes.HeaderRow.FindControl("drpOwners") as DropDownList;
DropDownList drpCompanyName = this.grdOtherQuotes.HeaderRow.FindControl("drpCompanyName") as DropDownList;
var filteredList = (from x in allQuotes
where (drpOwners.SelectedValue != ALL) ? x.SalesRepFullName == drpOwners.SelectedValue:true
&& drpCompanyName.SelectedValue != ALL ? x.CompanyName == drpCompanyName.SelectedValue: true
select x);
You could create a helper method that handles the All logic. Something like:
Then your query could be:
Create extension method(s) which encapsulate the where logic so it looks cleaner:
Personally, I'd find having this broken up to be simpler:
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:
This would then let you write this as:
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).