I'm trying to get values from numerous dropdown lists and build a where statement depending on the options selected. If they are not slected then they should be excluded from the select statement.
This is how I would have done it but I gather that it can not be done in this way with linq.
IEnumerable<IGrouping<string, Forest>> treeQuery =
from trees in Forest
if (ddlType1.SelectedValue!=null)
{
string strWhere += trees.Type1 == ddlType1.SelectedValue
}
else if (ddlType2.SelectedValue!=null)
{
string strWhere += trees.Type2 == ddlType2.SelectedValue
}
where strWhere
orderby trees.Nuts
group trees by trees.TrunkColour;
Any help would be greatly appreciated.
This is the code before I added the example in...
IEnumerable<IGrouping<string, Forest>> treeQuery =
from trees in Forest
where trees.Type1 == "oak"
orderby trees.Nuts
group trees by trees.TrunkColour;
For each one of your dropdowns, you can add a clause to your where:
where (ddlType1.SelectedValue == "" || trees.Type1 == ddlType1.SelectedValue)
&& (ddlType2.SelectedValue == "" || trees.Type2 == ddlType2.SelectedValue)
// && ( type 3... )
In this situation you can use the compositional nature of queries, but you don't want to use query expressions. So:
// Or IEnumerable<Forest>, depending on the type involved...
IQueryable<Forest> query = Forest;
if (ddlType1.SelectedValue!=null)
{
query = query.Where(trees => trees.Type1 == ddlType1.SelectedValue);
}
else if (ddlType2.SelectedValue!=null)
{
query = query.Where(trees => trees.Type2 == ddlType2.SelectedValue);
}
var finalQuery = query.OrderBy(trees => tree.Nuts)
.GroupBy(trees => trees.TrunkColour);
This won't actually execute the query until you start using the results - so you can add filtering, ordering etc bit by bit until you're "ready to go".
As this only involves two conditions you could do it in a single LINQ query as such:
Forest.Where(tree =>
(
(ddlType1.SelectedValue == null || tree.Type1 == ddlType1.SelectedValue) &&
(ddlType2.SelectedValue == null || tree.Type2 == ddlType2.SelectedValue)
))
.OrderBy(tree => tree.Nuts)
.GroupBy(tree => tree.TrunkColour);
Although as the number of conditions increases, it's worth splitting out the query into seperate parts for improved readability as this format can potentially get unreadable fast with multiple variables.